I have an external library that renders some custom js controls. The library returns a DOM element that can be inserted in to the page.
I am creating wrapper for this library in React. I have it all wired up except I'm not sure how to allow the render function to accept the DOM element as its return
render() {
if (this.state.someType) {
let customControl = new this.state.someType();
var node = customControl.getNode();
return node; //This is an HTMLDOMElement i.e. div or span
}
return <div>Loading Custom Control...</div>;
}
I am able to debug the code and everything is working properly. The node is what I expect but the html on the page is never replaced.
Rendering an Element in React: In order to render any element into the Browser DOM, we need to have a container or root DOM element. It is almost a convention to have a div element with the id=”root” or id=”app” to be used as the root DOM element.
React renders HTML to the web page by using a function called render(). The purpose of the function is to display the specified HTML code inside the specified HTML element. In the render() method, we can read props and state and return our JSX code to the root component of our app.
Here's a simple example.
render() {
const newNode = document.createElement('p');
return <div ref={(nodeElement) => {nodeElement && nodeElement.appendChild(newNode)}}/>
}
Render a normal JSX div
. Use ref
inside.
Inside the ref
callback use .appendChild(node)
See https://reactjs.org/docs/refs-and-the-dom.html
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