Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return DOM element in render function of React component

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.

like image 754
SirPyros Avatar asked May 10 '17 20:05

SirPyros


People also ask

How do I render DOM elements in React?

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.

What does the render method of a React component return?

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.


2 Answers

Here's a simple example.

render() {
   const newNode = document.createElement('p'); 
   return <div ref={(nodeElement) => {nodeElement && nodeElement.appendChild(newNode)}}/>
}
like image 185
Stanislav Mayorov Avatar answered Oct 08 '22 02:10

Stanislav Mayorov


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

like image 39
Walle Cyril Avatar answered Oct 08 '22 00:10

Walle Cyril