Categories
React Answers

How to Add a Tooltip div with React?

Spread the love

Sometimes, we want to add a tooltip div with React.

In this article, we’ll look at how to add a tooltip div with React.

Add a Tooltip div with React

To add a tooltip div with React, we can show or hide an element depending on the hover state of another element.

To add it, we write:

import React, { useState } from "react";

export default function App() {
  const [hover, setHover] = useState();

  const handleMouseIn = () => {
    setHover(true);
  };

  const handleMouseOut = () => {
    setHover(false);
  };

  return (
    <div>
      <div onMouseOver={handleMouseIn} onMouseOut={handleMouseOut}>
        hover me
      </div>
      <div>
        <div
          style={{
            display: hover ? "block" : "none"
          }}
        >
          tooltip
        </div>
      </div>
    </div>
  );
}

We defined the hover state with the useState hook.

And we use the setHover function to set the hover state to true and false in the handleMouseIn and handleMouseOut functions respectively.

We set handleMouseIn function as the onMouseOver handler and we set handleMouseOut as the onMouseOut handler.

This way we set hover to true to show the tooltip div when we hover over the hover me div or hide it when we move our mouse outside of the div.

The tooltip div’s display CSS property is controlled by hover‘s value.

If it’s true, we set it to 'block' to show it.

Otherwise, we set it to 'none' to hide it.

Conclusion

To add a tooltip div with React, we can show or hide an element depending on the hover state of another element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *