Reputation: 960
It's simple. I have a render function with two elements
render() {
let elem1 = <div>Foo</div>;
let elem2 = <div>Bar</div>;
return(elem1 + elem2); // How do I render elem1 below elem2?
}
I want the output to be equivalent to this
<div>
Foo
</div>
<div>
Bar
</div>
Upvotes: 1
Views: 1087
Reputation: 961
Extending on @Martin's answer above: If you are starting with latest version of React you should try and use React.Fragment
as grouping element. Here is the reactjs documentation for it: https://reactjs.org/docs/fragments.html
There is also a shorter syntax for React.Fragment
which is <>{elements}</>
. However support for short syntax is not fully available yet.
Here is a codepen link for problem you are trying to solve: https://codepen.io/bdevapatla/pen/QxaKEq
Upvotes: 0
Reputation: 13
You can just return the two elements in the render method instead of declaring them and return them directly. Like this
render() {
return (
<div>
<div>Foo</div>
<div>Bar</div>
</div>
)
}
Upvotes: 0
Reputation: 21
If you are using React > 16.2 you can use the new Fragment component
render() {
let elem1 = <div>Foo</div>;
let elem2 = <div>Bar</div>;
return (
<React.Fragment>
{elem1}
{elem2}
<React.Fragment/>
);
}
The main advantage over using a div is that it doesn't add any elements to the page and is more readable than returning an array.
Upvotes: 1
Reputation: 1928
render() {
let elements=new Array();
elements.push(<div>Foo</div>);
elements.push(<div>Bar</div>);
return elements;
}
So basically you can return array of children.
Upvotes: 0
Reputation: 518
Simple like this:
render() {
let elem1 = <div>Foo</div>;
let elem2 = <div>Bar</div>;
return (
<div>
{elem1}
{elem2}
</div>
);
}
You should read and practice more JSX in here
Upvotes: 3