Home > Mobile >  Setting HTML in a data attribute in Reactjs
Setting HTML in a data attribute in Reactjs

Time:03-23

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 role="tooltip"><div ></div><div ></div></div>'

Is this approach right or wrong?

CodePudding user response:

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  role="tooltip"><div ></div><div >${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>

CodePudding user response:

There is your answer:

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

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

export default App;

CodePudding user response:

You just pass attribute like this:

data-bs-template={

"<div  role="tooltip">
<div ></div>
<div ></div>
</div>"

}

Updated Code

  • Related