Reputation: 3159
I'm converting a html string to React element using the DOM parser and render it in my component.
I'm unable to use the dangerouslySetElements method as we are using sanitize html to encode any html tags and hence this usage render raw html with tags.
code:
function() {
const element = (
<div>
<span>test232></span>
<label>ahddgd</label>
</div>
}
<span data-tip-react data-tip = {ReactDOMServer.renderToString(element)}>test</span>
test() {
let section;
tipValue = targetNode.getAttribute("data-tip");
const doc = new DOMParser().parseFromString(tipValue, "text/xml");
section = (doc.childNodes[0]);
}
and this is the o/p I get for section
:
now when I try to render this in my component, it throws this error:
render() {
return (
<div>{section}</div>
)
}
Objects are not valid as a React child (found: [object Element]). If you meant to render a collection of children, use an array instead.
Any idea how to convert the above o.p that would render as react comp.? Unfortunately im also unable to use any third party lib..:(
Upvotes: 2
Views: 1536
Reputation: 4557
Yes, it is possible using dangerouslySetInnerHTML
, but it is not recommended.
From the docs:
dangerouslySetInnerHTML is React’s replacement for using innerHTML in the browser DOM. In general, setting HTML from code is risky because it’s easy to inadvertently expose your users to a cross-site scripting (XSS) attack. So, you can set HTML directly from React, but you have to type out dangerouslySetInnerHTML and pass an object with a __html key, to remind yourself that it’s dangerous.
Here is a working example how this could be done:
const {useState, useEffect} = React;
function App(){
const [data, setData] = useState("Loading...");
useEffect(()=>{
const containerInnerHTML = document.querySelector('#element').innerHTML;
setData(containerInnerHTML);
},[]);
return <div dangerouslySetInnerHTML={{__html: data}}/>;
}
ReactDOM.render(<App/>,document.getElementById('app'));
#element {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<div id='app'></div>
<div id="element">
<div>node 1</div>
<div>node 2</div>
</div>
Hope this helps!
Upvotes: 1