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.
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.
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'));
CodeSandbox
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With