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

StackOverflow https://stackoverflow.com/questions/22280315

  •  11-06-2023
  •  | 
  •  

Question

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.

Était-ce utile?

La solution

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

Autres conseils

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);

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top