'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?
Solution 1:[1]
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')
);
Solution 2:[2]
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'));
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | NamedAfterALanguage |
