Setting HTML in a data attribute in Reactjs

643 Views Asked by At

I can not figure it out that how is it possible to use HTML in a data attribute inside React's jsx.

Like

data-bs-template='<div class="tooltip d-none d-md-block" role="tooltip"><div class="arrow"></div><div class="tooltip-inner"></div></div>'

Is this approach right or wrong?

3

There are 3 best solutions below

1
On

In order set HTML in a React component, you need to create an object that has the __html property and the a string that contains the relevant HTML markup. Like this:

{__html: '<span>Something</span>'};

And finally render it using dangerouslySetInnerHTML which is React's replacement for the native innerHTML:

function Tooltip(props) {
  const someHTML = {
    __html: `<div class="tooltip d-none d-md-block" role="tooltip"><div class="arrow"></div><div class="tooltip-inner">${props.text}</div></div>`
  };
  return <div dangerouslySetInnerHTML={someHTML}></div>;
}

function App() {
  return (
    <div className="container">
      <Tooltip text="Hello this is a tooltip" />
    </div>
  );
}

ReactDOM.render( < App / > , document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>

0
On

There is your answer:

const App = () => {
 const data = '<b>lorem ipsum</b>';

 return (
   <div
     dangerouslySetInnerHTML={{__html: data}}
   />
 );
}

export default App;
2
On

You just pass attribute like this:

data-bs-template={

"<div class="tooltip d-none d-md-block" role="tooltip">
<div class="arrow"></div>
<div class="tooltip-inner"></div>
</div>"

}

Updated Code