Categories
React Projects

Create a Tooltip with React and JavaScript

Spread the love

React is an easy to use JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a tooltip with React and JavaScript.

Create the Project

We can create the React project with Create React App.

To install it, we run:

npx create-react-app tooltip

with NPM to create our React project.

Create the Tooltip

To create the tooltip, we write:

import React, { useState } from "react";

export default function App() {
  const [show, setShow] = useState(false);
  const [clientX, setClientX] = useState(0);
  const [clientY, setClientY] = useState(0);

  const onHover = (e) => {
    const { clientX, clientY } = e;
    setShow(true);
    setClientX(clientX);
    setClientY(clientY);
  };

  return (
    <div className="App">
      <style>
        {`
          #container {
            width: 95vw;
            height: 95vh;
            align-items: center;
            display: flex;
            justify-content: center;
          }

          #tooltip {
            border: 1px solid black;
            padding: 5px;
            position: absolute;
            background-color: white;
          }
          `}
      </style>
      <button onMouseOver={onHover}>hover me</button>
      {show && (
        <div
          id="tooltip"
          style={{ top: `${clientY}px`, left: `${clientX}px` }}
          onMouseOut={() => setShow(false)}
        >
          tooltip
        </div>
      )}
    </div>
  );
}

We have the show , clientX and clientY states that lets us set whether to show the tooltip, and its position respectively.

Next, we define the onHover function.

It gets the clientX and clientY values from the mouse event object.

Then call setShow to show the tooltip.

And setClientX and setClientY sets the position of the tooltip.

Next, we add the styles for the tooltip.

We make its position absolute so that it can show on top of other items.

The hover me button runs onHover when we hover over it.

And then we display the tooltip div if show is true .

We set the style prop to an object with the top and left positions to set the tooltip position.

onMouseOut is set to a function that calls setShow with false to hide the tooltip.

Conclusion

We can create a tooltip easily with React and JavaScript.

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 *