Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

when multiple React DOM components are used without outer div then JSX won't compile

Consider this example which won't compile:

/** @jsx React.DOM */

var Hello = React.createClass({
  render: function() {
    return <div>Hello</div>;
  }
});

var World = React.createClass({
  render: function() {
    return <div>World</div>;
  }
});

var Main = React.createClass({
  render: function() {
    return (
        <Hello />
        <World /> 
    );
  }
});

React.renderComponent(<Main />, document.body);

But any of these combinations does work:

<div>
 <Hello />
 <World />
</div>

 <Hello />
 //<World />

 //<Hello />
 <World />

Wanted to know if multiple components should always be surrounded by div tags.

like image 355
Raja Avatar asked Mar 09 '14 09:03

Raja


3 Answers

I think the render function should return only one component.

From the docs: http://facebook.github.io/react/docs/component-specs.html

The render() method is required.

When called, it should examine this.props and this.state and return a single child component

like image 156
Raja Avatar answered Oct 05 '22 23:10

Raja


There's a simple way to get around this limitation:

var Hello = React.createClass({
  render: function() {
    return <div>Hello</div>;
  }
});

var World = React.createClass({
  render: function() {
    return <div>World</div>;
  }
});

var HelloWorld = [Hello, World];

var Main = React.createClass({
  render: function() {
    return (
        {HelloWorld}
    );
  }
});

React.renderComponent(<Main />, document.body);
like image 41
Gerson Goulart Avatar answered Oct 05 '22 23:10

Gerson Goulart


React components can only render a single root node. If you want to return multiple nodes they must be wrapped in a single root.

As specified on the Official React Site: React Docs

like image 38
myusuf Avatar answered Oct 05 '22 23:10

myusuf