user7456879
user7456879

Reputation:

Javascript ReactJs render multiple components in the same div

I am starting up on ReactJs and I have 2 components snd a render call below:

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

var Hello2 = React.createClass({
  render: function() {
    return <div>Hello2 {this.props.name}</div>;
  }
});

ReactDOM.render(
  <Hello name="World" />,
  document.getElementById('container')
);

Is it posible to render both components in container?

I've tried:

ReactDOM.render(
  <Hello name="World" />,
  <Hello2 name="World2" />,
  document.getElementById('container')
);

But that didn't work.

How can I do this?

Upvotes: 2

Views: 3468

Answers (3)

NamedAfterALanguage
NamedAfterALanguage

Reputation: 1

You can wrap your two components into another component without adding any DOM elements, since React.Component.render() can handle arrays (see https://reactjs.org/docs/react-component.html#render).

"use strict";
class Hello extends React.Component {
   render() {
      return(React.createElement('div',null,`Hello ${this.props.name}`));
   }
}
class Hello2 extends React.Component {
   render() {
      return(React.createElement('div',null,`Hello2 ${this.props.name}`));
   }
}
class Container extends React.Component {
    render() {
        return([
           React.createElement(Hello, {name: "World", key: "one"}),
           React.createElement(Hello2, {name: "World", key: "two"})
        ]);
    }
}
ReactDOM.render(React.createElement(Container),document.getElementById('container'));

Upvotes: 0

Mayank Shukla
Mayank Shukla

Reputation: 104529

You can render only one component, if you want to render multiple then wrap them in a div or any other wrapper element, Use this code:

ReactDOM.render(
  <div>
     <Hello name="World" />
     <Hello2 name="World2" />
  </div>
  document.getElementById('container')
);

Or we can also make use of array here, but don't forget to assign keys. Like this:

ReactDOM.render(
  [
     <Hello name="World" key={0} />
     <Hello2 name="World2" key={1} />
  ]
  document.getElementById('container')
);

Update:

With React 16+, we can use React.Fragment, benefit will be, it will not add any extra node in dom. Like this:

ReactDOM.render(
  <React.Fragment>
     <Hello name="World" />
     <Hello2 name="World2" />
  </React.Fragment>
  document.getElementById('container')
);

Upvotes: 2

prosti
prosti

Reputation: 46479

You must wrap these into a container, else not possible.

ReactDOM.render(
  <div>
  <Hello name="World" />
  <Hello2 name="World2" /> 
  </div>,
  document.getElementById('container')
);

Upvotes: 0

Related Questions