5

Is it possible to render an element based on a IF/OR statement?

I tried something like:

{!this.props.this || this.props.that && <button>Some button</button>}

but that doesn't work.

2
  • 1
    condition ? <component> : null Commented Jan 25, 2018 at 22:05
  • What Josiah asid or you can run an IIFE that returns the component or JSX you want to render based on your conditional block. Commented Jan 25, 2018 at 22:06

3 Answers 3

14

Yes, it's possible. Use ternary operator:

{ 
  (!this.props.this || this.props.that) ? <button /> : null
}

You can also use React.Fragment to render more complex elements structure without container, for example

{
  this.props.test ? (
    <React.Fragment>
      <ChildA />
      <ChildB />
      <ChildC />
    </React.Fragment>
  ) : null
}

Note, that when you return null React treats it as nothing to render.

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

1 Comment

Note that fragments are a new feature introduced in React 16. I've been waiting for them for a while!
4

I assume you want to know the equivalent of

if (!this.props.this || this.props.that) {
  // Render the button
}

The reason your code doesn't work that way is because of the precedence of && and ||. The && is evaluated first, but you really want the combined condition to evaluate first.

You could use a ternary as others have suggested, but all you technically need is parentheses

{(!this.props.this || this.props.that) && <button>Some button</button>}

That way, you don't need a redundant null

Comments

0

The official documentation on this is pretty good. I find it cleanest to use ternary operators, which work as follows:

{(!this.props.this || this.props.that) ? <button>Some button</button> : null }

You can of course have a different component render if false instead of just null.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.