Search code examples
javascriptreactjsreact-dom

How to show tooltip with jsx content inside it-Reactjs


I want to show a tooltip on hover, that tooltip has html jsx content. I used ReactDOMServer.renderToStaticMarkup to convert the jsx to string however the end result of the tooltip is :

<div>ABC</div>
 <div>ABC description</div>
  <div>ABC refreshed 1 min ago</div>

I want the tooltip to show the content within the html and not include the tags. How can I do that?

jsx:

render() {
  let tooltip = (
  <div>ABC</div>
 <div>ABC description</div>
  <div>ABC refreshed 1 min ago</div>
)
  return (
      <div><span data-tip={ReactDOMServer.renderToStaticMarkup(tooltip)}>ABC info</span></div>
  )
}

Solution

  • Put it in a normal html element and use a css selector to show it when the other element is hovered. Here is an example:

    .element {
      position: relative;
    }
    
    .tooltip {
      display: none;
      position: absolute;
      top: 100%;
      left: 0;
      padding: 3px;
      border: 1px solid black;
    }
    
    .element:hover .tooltip {
      display: block;
    }
    <span class="element">
      Hover me
      <span class="tooltip">I appear on hover!</span>
    </span>

    This is very simple and does not need any js logic in React.