TmKVU
TmKVU

Reputation: 3000

Render react component into single DOM element

When rendering a React component, one has to place this component into a DOM element already present in the document, e.g:

React.render(<MyComponent />, document.findElementById('container'));

However, the render function of a component must always return a single node, resulting in the following DOM structure:

<div id='container'>
   <div id='myComponent'>
      <!-- Stuff in the component -->
   </div>
</div>

This is creating unnecessary DOM elements, since the outer container could just as well be emitted given it has not additional value for the structure of the document.

As for now, one can not render multiple components into the same parent(for example the body):

React.render() replaces the contents of the container node you pass in. In the future, it may be possible to insert a component to an existing DOM node without overwriting the existing children.

Is there some other way to render components without any unnecessary parent nodes? Thanks in advance!

Upvotes: 2

Views: 2964

Answers (1)

pSaadi
pSaadi

Reputation: 300

There is no other way. You always need a root node

https://facebook.github.io/react/tips/maximum-number-of-jsx-root-nodes.html

Why don't you get rid of the cointainer and render your component straight to the body?

React.render(<MyComponent />, document.getElementsByTagName('body')[0]);

Upvotes: 1

Related Questions