How to add a tooltip in React
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
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.
1 | 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | import React from 'react'; import ReactTooltip from "react-tooltip"; function App() { return ( <div className="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" /> </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.
That’s it for today.
Thank you for reading. Happy Coding..!!