Clue Mediator

How to add a tooltip in React

📅June 13, 2020

When you are working with jQuery or a JavaScript HTML page then it’s easy to implement tooltip but It's a little bit complex to implement tooltip same as jQuery therefore today we’ll show you how to add tooltip in React application.

In this article, we will use the `react-tooltip` npm package to create a demo for the explanation. You can also find more examples that were created using the npm package.

Steps to implement a tooltip in React

  1. Create a react application
  2. Install npm package
  3. Add tooltip in component
  4. Output

1. Create a react application

First, we have to create a startup react application in which we can implement the demo. Refer to this article for more explanation.

2. Install npm package

As we mentioned previously, we will use the react-tooltip npm package so use the following command to install it in the react application.

npm i react-tooltip

3. Add tooltip in component

To add a tooltip in the react component, we have to first import a react-tooltip at the top of the react component.

import React from 'react';
import ReactTooltip from "react-tooltip";

function App() {
  return (
    <div class="App">
      <h3>How to add a tooltip in React</h3>
      <p data-tip="Like, Subscribe and Share!" data-event="click">Clue Mediator</p>
      <a href="https://www.cluemediator.com" target="_blank" data-tip="Click to visit Clue Mediator" rel="noopener noreferrer">www.cluemediator.com</a>
      <reacttooltip globaleventoff="click">
    </reacttooltip></div>
  );
}

export default App;

In the above code, we have displayed two different types of the tooltip. One is to display a tooltip on click and the second one is to display a tooltip on mouse hover.

We have passed the tooltip content in `data-tip` attribute for display purpose and set the `data-event="click"` attribute to show the tooltip on click event.

Also, we have set the `globalEventOff="click"` to hide the tooltip on document click. The single `ReactTooltip` component will work for multiple tooltips.

This package itself provides several options to configure a tooltip. Check out this link for more options.

This demo will work for both React component and React Hooks applications.

4. Output

Let’s run the project and check out the output in the browser.

Output - How to add a tooltip in React - Clue Mediator

Output - How to add a tooltip in React - Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!

Demo & Source Code

Github Repository StackBlitz Project