Let’s create a tooltip with React hooks

Ismayil Khayredinov
ITNEXT
Published in
1 min readFeb 1, 2020

--

I have written recently about DIY popup elements in React. Let’s use that knowledge to create a reusable React tooltips using function components and React hooks.

Let’s start by creating a simple hook that will allow us to toggle visibility of an element.

As you can see, in this example, we are exporting an event handler that can toggle the state of the element.

Let’s go a step further and instantiate a new popper instance and export the necessary references.

We are now using a React effect to create and destroy a popper instance when component mounts and unmounts. We store the popup instance in our state and perform updates whenever needed.

Let’s add some styling and add more event handlers to toggle the popup on mouse and focus events.

Let’s now extract our tooltip logic into a separate component we can reuse multiple times:

That’s it. You now have a functioning Tooltip component you can reuse wherever you want in your application.

--

--

Full-stack developer, passionate about front-end frameworks, design systems and UX.