Hiding further information behind an interaction with an icon, button, or text is a good way of making your interface clean and tidy. This is where tooltips and pop-up menus come into play.
This article will introduce you to the approach I followed to implement a tooltip controller component in React. Although I call it tooltip, it can be anything that you want to display when an element inside the DOM is interacted with via a click or hover.
I will only be covering the fundamentals here. However, if you are interested in seeing the detailed functionalities, check out the Github repository for the full project.
This is a feature-rich React component for controlling tooltips. Not only for tooltips, but you can use it for various interaction requirements. It seamlessly integrates into your markup without breaking it. Visit the examples page to discover the functionalities. Basic Tooltip Animated Tooltip Advanced Tooltip Highlights Supports click, hover, hover-hold and hover-interact detections.
Let’s start by listing some basic requirements for the tooltip controller component.
- It should seamlessly integrate into the existing JSX markup
Being able to integrate the component into your existing JSX without introducing extra HTML elements such as
is important in the sense that it does not affect the JSX output and styling consequently.
- It should appear on top of all the other elements
It is obvious that the tooltip should not appear under any other elements inside the DOM. Using z-index might not help you in some cases since its use is just not as straightforward as it seems. Therefore the tooltip should appear at the very bottom of the
to guarantee its hierarchy at the top of the DOM tree.
- It should be interactive when needed
A passive tooltip showing just text or an image usually does not require any interaction. It might even be expected to close when clicked. But the example shown above, for instance, requires the tooltip to stay active when clicked on to use the buttons/links inside it.
Consider the following code blocks and assume that we want to create an interaction on one of the li elements
Wrapping this specific
<li> element along with the tooltip component, which we want to control, is the approach that we will follow.
This will give us the flexibility of having full control of both the selected element and the tooltip component or JSX markup that we included inside the
We can add event listeners, control styling, fetch position information, etc. When you have one or several components wrapped by another component, this design pattern is usually referred to as Compound Components.
We will create two components:
<Controller> will hold the part of the code that we want to talk to each other; tooltip and the selected element.
<Select> component, on the other hand, will only handle the selected DOM element, which will control the tooltip.
<Controller> component will wrap two children, we will use the following React APIs to deal with these children.
React.Children is one of the React APIs used to handle children props of a component, meaning that anything wrapped by a component can be accessed as a prop inside a component. Calling
map method on
this.props.children helps us to iterate over it and create a new array of modified children out of it.
This API creates a clone of the input and returns a new react element. Combining this with
React.Children gives us the ability to manipulate the child components of the
<Controller> component that we are going to implement.
Since we aim to mount the tooltip component at the very bottom of the
body, we need to somehow prevent React from appending it to the nearest parent node by default. Portal is the native solution provided by React. We can specify where and which element to mount in the DOM.
Start with the basics
Before we start to implement detailed functionalities, let’s quickly take a look at the basic structure of the
Notice the use of
map function to iterate over all the children and return a clone of each child with
Also, use of
React.createPortal is straightforward, it takes the cloned child and renders it to
document.body, which returns the
<body> element in the DOM.
Note that in order to distinguish between children of the
<Controller>, I used
displayName property, which will be defined as a static property in the
<Select> component later.
The next step is adding the following functionalities.
- Add an event listener to the selected element in order to control the tooltip
- Position the tooltip relative to the selected element
- Detect click outside of the tooltip component to close it
- Prevent the tooltip from bubbling events, so that it does not close when clicked on it
1. Open the tooltip
Start off with creating the state of
isOpen is for mounting and unmounting the tooltip component/JSX markup and
style is for positioning the tooltip relative to the selected element. The tooltip is absolutely positioned relative to body by default. So, by obtaining the position and size information of the selected element, we can position the tooltip relative to it.
Now, create the functions controlling the state of the tooltip
Next, this is using
style states to show/hide and position the tooltip component respectively. Also, it is required to pass the
open() function to
<Select> component as a prop so that when the selected element is clicked, we can show the tooltip.
The second argument for
React.cloneElement is the new props we are passing to
Let’s take a look at the
<Select> component and see how we handle the cloned child and props.
Notice the static definition of
displayNamethat we previously used in
Although we could simply do
return children in the render method of
<Select> component, the use of
cloneElement API gives us the ability to create a new clone of the children prop with
onClick event handler.
And we assign the
open prop to this
onClick event handler to call the
open() function in the
<Controller> component, which, as a result, shows the tooltip at the top left corner of the screen.
Now, it’s time to get the position and size information of the cloned child element inside the
<Select> component and pass this data back to
<Controller> to be used with
style state to position the tooltip.
2. Position the tooltip
Getting the position of the element inside the
<Select> component requires use of
ref attribute. ReactJS has its own way of creating refs. Once you define a
ref by using
React.createRef() and attach it to an element, you can refer to it throughout the component.
getBoundingClientRect() method on the
selectedElement ref returns both the position and size information of the element. We will pass this information from
<Select> component to
<Controller> component by deploying a function as a prop on
getPos() function is available to
<Select> component as a prop, calling it inside the
componentDidMount life-cycle hook updates the
style state variable of
<Component> and positions the tooltip relative to left-bottom of the selected element.
3. Close the tooltip
So far, we controlled the tooltip through a selected element and positioned it relative to this element. Now, the next thing is implementing the mechanism for closing the tooltip when clicked outside of it.
It is quite straightforward to listen to click events on
window object and toggle the
isOpen state variable. However, this approach requires some small tricks to make it work properly.
Consider the following snippet from
When the component is updated, we either add or remove an event listener for
window object in accordance with the state of the tooltip. However, this attempt results in a tooltip opening and closing virtually simultaneously.
I came up with two different solutions to this problem:
- Instead of listening to
clickevent both for
close()functions, listening to
open()functions respectively prevents the
close()function being called, since it listens to
mousedownevent which happened before the tooltip was opened.
However, this approach fails if you try to close the tooltip by clicking on the selected element.
2. This second approach is a bit more advanced in terms of the reasoning behind it. Using
setTimeout method with
0 milliseconds delay or without any time delay defined queues a new task to be executed by the next event loop. Although using
setTimeout is used, it simply creates an asynchronous callback. You can refer to the specific MDN web docs for a detailed explanation on the topic.
The snippet below ensures that an event listener will be added or removed after the interaction tasks with selected element are executed.
Although clicking on the selected element calls the
open() function, event listener on the
window object calls the
close() function after and closes the tooltip.
4. Prevent event bubbling
As mentioned earlier, in some specific cases you might need to prevent the tooltip from closing when clicked on it. The reason clicking on the tooltip calls the
close() function is the result of the event bubbling.
When an event, such as
onClick, happens on an element, it also gets called on the parent and all the other ancestors. In our case, since tooltip is a child of the
body has a click event attached, clicking on the tooltip calls the function attached to click event on the
In order to prevent this phenomenon, we need to explicitly specify on the click handler of the child element that the events should not bubble further up to ancestors.
event.stopPropagation() method is what we need to use on
onClick event handler to stop propagation of
onClick events further up in the DOM.
After reading through this article, you should get familiar with the mentioned React APIs and have an overall idea on how to utilize and combine them to structure compound components for more specific tasks. Having different components talk to each other internally can make your code more structured and purposeful.
Plug: LogRocket, a DVR for web apps
LogRocket is a frontend logging tool that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.