When multiple React DOM components are used without an external div, JSX will not compile

Consider this example that will not 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 work:

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

 <Hello />
 //<World />

 //<Hello />
 <World />

You need to know whether you should always be surrounded by div tags.

+4
source share
3 answers

I think that the render function should return only one component.

From the docs: http://facebook.imtqy.com/react/docs/component-specs.html

The render () method is required.

When called, it should check this.props and this.state and return one child component

+7
source

There is an easy way 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);
+4
source

Responsive components can display only one root node. If you want to return several nodes, they must be wrapped in one root.

As indicated on the official React: React Docs website

+1
source

Source: https://habr.com/ru/post/1530813/


All Articles