Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ternary operator in return statement that returns an array

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.

like image 889
left click Avatar asked Oct 15 '25 03:10

left click


2 Answers

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.

like image 139
Kyle Richardson Avatar answered Oct 16 '25 17:10

Kyle Richardson


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

like image 23
Shubham Khatri Avatar answered Oct 16 '25 16:10

Shubham Khatri