4

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.

1
  • I made a foolish mistake lol !! Thank you to everyone. Commented Dec 16, 2017 at 17:41

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

@ibrahimmahrir I didn't say it will create an object, I said it will be treated as an object, and since the syntax inside the object is invalid it throws an error
2

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];
    }
}

Comments

0

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.

2 Comments

You can't do this in React. You'd need a single parent or use an array.
Sorry forgot div wrapper

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.