React Tooltip Component

In another snippet, we already know how to create a tooltip with HTML and CSS. See more detail => Create CSS tooltip for all positions

Today we will use all of those codes to create a React Tooltip Component to reuse in a React App.

Step 1: Create a CSS file call styles.css with the CSS codes below:

 .tooltip {
  position: relative;
  display: inline-block;
}
.tooltip .tooltip-text {
  visibility: hidden;
  width: 120px;
  background-color: #555;
  color: #fff;
  text-align: center;
  border-radius: 6px;
  padding: 5px 0;
  position: absolute;
  z-index: 1;
  opacity: 0;
  transition: opacity 0.3s;
}
/* Tooltip top content */
.top .tooltip-text {
  bottom: 100%;
  left: 50%;
  margin-left: -60px; /* 120/2 = 60 */
}
/* Tooltip right content */
.right .tooltip-text {
  top: -5px;
  left: 110%;
}
/* Tooltip bottom content */
.bottom .tooltip-text {
  top: 100%;
  left: 50%;
  margin-left: -60px; /* 120/2 = 60 */
}
/* Tooltip left content */
.left .tooltip-text {
  top: -5px;
  right: 110%;
}
.tooltip .tooltip-text::after {
  content: "";
  position: absolute;
  border-width: 5px;
  border-style: solid;
}
/* Tooltip top arrow */
.top .tooltip-text::after {
  margin-left: -5px;
  left: 50%;
  top: 100%;
  border-color: #555 transparent transparent transparent;
}
/* Tooltip bottom arrow */
.bottom .tooltip-text::after {
  margin-left: -5px;
  bottom: 100%;
  left: 50%;
  border-color: transparent transparent #555 transparent;
}
/* Tooltip left arrow */
.left .tooltip-text::after {
  top: 50%;
  margin-top: -5px;
  left: 100%;
  border-color: transparent transparent transparent #555;
}
/* Tooltip right arrow */
.right .tooltip-text::after {
  top: 50%;
  margin-top: -5px;
  right: 100%;
  border-color: transparent #555 transparent transparent;
}
.tooltip:hover .tooltip-text {
  visibility: visible;
  opacity: 1;
}


Step 2: Create a React component call Tooltip.js:





Step 3:
Use in your React app like this




Note:
- In the example above, we use the position property is "top" that mean the tooltip content will be display on the top position of your element, you can change to "left", "right", "bottom".
- The content property of the Tooltip component is the content that you want to display inside tooltip.

© 2019 4codev

Created with love by Sil.