Reputation: 79
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
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
Upvotes: 1