Is there a way to render multiple React components in the React.render() function?

Bryan Grace picture Bryan Grace · Sep 15, 2015 · Viewed 89.8k times · Source

For example could I do:

import React from 'react';
import PanelA from './panelA.jsx';
import PanelB from './panelB.jsx';

React.render( 
  <PanelA />
  <PanelB />, 
  document.body  
);

where React would render:

body
   PanelA
   PanelB

Currently I'm getting the error:

Adjacent JSX elements must be wrapped in an enclosing tag

while transpiling with browserify and babelify

Answer

David Ginanni picture David Ginanni · Sep 27, 2017

Since the React v16.0 release you can render an array of components without wrapping items in an extra element when you are inside a component:

render() {
  return [
    <li key="one">First item</li>,
    <li key="two">Second item</li>,
    <li key="three">Third item</li>,
    <li key="four">Fourth item</li>,
  ];
}

Remember only to set the keys.

UPDATE

Now from the 16.2 version you can use the Fragments

  render() {
    return (
      <React.Fragment>
        <td>Hello</td>
        <td>World</td>
      </React.Fragment>
    );
  }

Short syntax

  render() {
    return (
      <>
        <td>Hello</td>
        <td>World</td>
      </>
    );
  }

In the ReactDOM.render you still can't render multiple items because react needs a root. So you can render a single component inside the ReactDOM.render and render an array of items in the internal component.