Reputation: 894
I use React 16.0.
I want to return an element conditionally as shown below.
import React from 'react';
export default class App extends React.PureComponent {
render () {
return [
<div className="a"></div>,
{condition ? <div className="b"></div> : null},
{condition ? <div className="c"></div> : null}
];
}
}
Is there a way to do this without any extra methods or conditional statements outside the return statement?
thank you for reading.
Upvotes: 4
Views: 4974
Reputation: 1867
It looks like you basically have it!
import React from 'react';
export default class App extends React.PureComponent {
render () {
return (
<div>
<div className="a"></div>
{condition ? <div className="b"></div> : undefined}
{condition ? <div className="c"></div> : undefined}
</div>
);
}
}
This will render the first div no matter what, and then only the second and third based on "condition" being true.
Upvotes: 0
Reputation: 34914
You can simply do it as
export default class App extends React.PureComponent {
render () {
var b = condition ? <div className="b"></div> : null;
var c = condition ? <div className="c"></div> : null;
return [<div className="a"></div>,b,c];
}
}
Upvotes: 2
Reputation: 281874
You don't need to wrap your condition within {}
otherwise it makes it an object within array. Also you need to specify unique keys for each item in the array.
const condition = true;
export default class App extends React.PureComponent {
render() {
return [
<div key="a" className="a">a</div>,
condition?<div key="b" className="b">b</div> : null,
condition?<div key="c" className="c">c</div> : null
];
}
}
render(<App />, document.getElementById('root'));
Upvotes: 2
Reputation: 5645
You're inside an array, not JSX. There is no need to use the curly braces, just do your ternary operation and then put a comma after it.
return [
<div className="a"></div>,
condition ? <div className="b"></div> : null,
condition ? <div className="c"></div> : null
];
Keep in mind, this will create indices with null as their value in the array if the conditions are false.
Upvotes: 5