Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

react use dangerouslySetInnerHTML to render json with html tags

I am trying to render a json list with html tags in the string in a list as follows jsbin. It works in Jsbin. But in my console I got warning below:

warning  Only set one of `children` or `props.dangerouslySetInnerHTML` react/no-danger-with-children

just wonder if there is other way to render the list with dangerouslySetInnerHTML to avoid the warning?

const displayList = [
    {
        item: 1,
        text: "<strong>ABC</strong> this should be strong."
    },
    {
        item: 2,
        text: "<a>ABC</a> this should be link."
    },
    {
        item: 3,
        text: "normal text"
    }
];

const App = () => (
    <ul>
        {displayList.map((item, i) => (
            <li key={i}>
                <div dangerouslySetInnerHTML={{
                    __html: item.text
                }}>
                </div>
            </li>
        ))}
    </ul>
);

ReactDOM.render(
    <App />,
    document.getElementById('root')
);
like image 716
zizi Avatar asked May 05 '17 02:05

zizi


People also ask

How do you render a string with HTML tags in React?

To render the html string in react, we can use the dangerouslySetInnerHTML attribute which is a react version of dom innerHTML property. The term dangerously is used here to notify you that it will be vulnerable to cross-site scripting attacks (XSS).

How render data from JSON in React?

Step 1: Open the terminal and create react app. Step 2: Change the directory to that folder by executing the command. Project Structure: It will look like the following. Step 3: Creating a JSON Object File here and Save it as data.


1 Answers

React is complaining about the use of dangerouslySetInnerHTML in conjunction with safe react children, that happened when you let the div tag opened to such characteristic <div>open and ready for children</div>.

Since you are using the JSX syntax extension, the solution here is write the whole sentence in a single line:

<div dangerouslySetInnerHTML={{__html: item.text}}></div>

or just using a singleton div tag:

<div dangerouslySetInnerHTML={{
       __html: item.text
     }}/>

By the way you are not getting the error on jsbin because it is a react production build, this build is not meant to tell you what could be written better.

like image 173
David De Anda Avatar answered Oct 11 '22 21:10

David De Anda