H.hashemi
H.hashemi

Reputation: 79

how to return string html as react child

I want to return my string as html for react child assuming string as "<div><span>test</span></div>" and assuming we have a react function component like below:

 function StrToElement({ str }) {  
 const element = new DOMParser().parseFromString(str, "text/html").body.childNodes[0];
 return <pre>{element}</pre>;
}

but the above code throws this error:

Error: Objects are not valid as a React child (found: [object Text])

Upvotes: 0

Views: 372

Answers (1)

kwaiks
kwaiks

Reputation: 143

You may use dangerouslySetInnerHTML property inside your element.

It will look like this

 function StrToElement({ str }) { 
   return <div dangerouslySetInnerHTML={{__html: str}}>{element}</div>;
 }

or maybe you could assign it directly without creating new component

Reference

Upvotes: 1

Related Questions