Using a short circuit evaluation in a functional component (with hooks):
JavaScript
x
14
14
1
const Filters = () => {
2
const [options, setOptions] = useState([]);
3
4
return (
5
<div className="row">
6
{options.length > 0 && (
7
<div className="col-md-3">
8
<CustomComponent />
9
</div>
10
)}
11
</div>
12
)
13
}
14
Is there a way to render multiple elements right after an inline if condition?
JavaScript
1
9
1
{options.length > 0 && (
2
<div className="col-md-3">
3
<CustomComponent />
4
</div>
5
<div className="col-md-3">
6
<SecondComponent />
7
</div>
8
)}
9
Code above doesn’t work, react throws an error. options
array is filled after a promise resolved from useEffect()
. That’s why i’ve added this check, to display elements only when a promise resolved.
UPDATED CODE for @wentjun:
JavaScript
1
10
10
1
return (
2
{options.length > 0 && (
3
<div className="row">
4
<div className="col-md-3">
5
<CustomComponent />
6
</div>
7
</div>
8
)}
9
)
10
This throws a syntax error.
Advertisement
Answer
You should wrap the elements in React Fragments. The reason being, React elements are rendered via a single root node element. Wrapping it in Fragments will allow you to group the elements without adding additional nodes.
JavaScript
1
15
15
1
return (
2
<div className="row">
3
{options.length > 0 && (
4
<>
5
<div className="col-md-3">
6
<CustomComponent />
7
</div>
8
<div className="col-md-3">
9
<SecondComponent />
10
</div>
11
</>
12
)}
13
</div>
14
)
15