Search code examples
reactjsdangerouslysetinnerhtml

How to use dangerouslySetInnerHTML


I have html script data.

I want to put it in div. but when I do that It just shows "}" this and that's it.

I wonder what I did wrong.

When I log newDataHTML, I can get html string.

import React, { useState, useEffect } from 'react';
import axios from 'axios';

function App() {

  const getData = () => {
    axios
      .get('/api/data')
      .then( (data) => {
        // get new Data
        const newDataHTML = data.data[0].rule;

        return {__html: newDataHTML};
      })
      .catch( err => console.log(err));
  }

  return (
    <div className="App">
      <Tabs defaultTab="data" onChange={(tabId) => { console.log(tabId) }}>
        <TabList>
          <Tab tabFor="data">New Data</Tab>
        </TabList>
        <TabPanel tabId="data">
          <div dangerouslySetInnerHTML={getData()}></div>;
        </TabPanel>
      </Tabs>
    </div>
  );
}

export default App;


Solution

  • It is not working because you can't return outside .then method and also you will encounter rerender loop... You can put the method in useEffect hook so it runs once and also put the return data in useState...

    const [data, setData] = useState();
    useEffect(() => {
       const getData = () => {
          axios.get('/api/data').then((res) => {
            const newDataHTML = res.data[0].rule;
            setData({__html: newDataHTML})
          }).catch( err => console.log(err));
       }
       getData();
    }, [])
    

    you can now use the data variable in your jsx instead of calling the function in your jsx.

    It will also be nice to use packages like DomPurify to avoid xss attacks.

    https://www.npmjs.com/package/dompurify