I am using Wordpress as my CMS and creating some of the pages in React and rendering it. I have a use case where i need to render HTML DOM Node inside of my React Component. I am getting the DOM Node with the help of querySelector() which returns me the DOM node. In React i am trying to render it using React.createElement. But it renders as [object HTMLDivElement] on my page.
render() {
const { reactPages } = this.props;
const innerPages = React.createElement('div', {id: "myDiv"}, `${reactPages.children[0]}`);
return (
<div className="react-cmp-container">
<h3>React Container</h3>
{ innerPages }
</div>
)
}
}
The other thing i tried was using the dangerouslySetInnerHTML:
rawMarkUp = () => {
const { reactPages } = this.props;
return {__html: reactPages}
}
render() {
const innerPages = React.createElement('div', {id: "myDiv"}, )
return (
<div className="react-cmp-particle-container">
<h3>React Particle Container</h3>
<div dangerouslySetInnerHTML={this.rawMarkUp()}></div>
</div>
)
}
This is the type of DOM Node that i am getting and passing it as props to my Component.
This is not recommended to to. It might cause many kinds of trouble later. Anyway, ...
querySelector()
returns a DOM-element
(or collection of such).
React.createElement
React.createElement
does not work, because it expects another React.Element
, or a string
, not a DOM-element
.
dangerouslySetInnerHTML
dangerouslySetInnerHTML
does not work, because it expects a HTML string, not a DOM-element
.
You could use domElement.innerHTML
and put the HTML string into dangerouslySetInnerHTML
, but that might not represent the DOM element as you want it.
useRef
You could add a ref
to some element that is rendered by React. This gives you access to the corresponding DOM-element
(rendered by React), and you can inject your DOM-element
(returned by querySelector()
) using normal DOM methods.
This disables React to "track what's going on", and you might experience inconsistent state and hard-to-understand bugs.
e.g.:
export const StaticHtml = (props)=>{
const ref = useRef();
useEffect(() =>{
var elm = document.getElementById('some-static-html');
ref.current.appendChild(elm);
}, []);
return (<div ref={ ref }>
some div
</div>);
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With