How to conditionally add a group of props to a react component?

Viewed 267

I have a group of props that I need to apply to a component only if a certain condition is met.
So I grouped the props in an object:

const props = {
  a: "",
  b: "",
};

And then tried to conditionally apply them to the component:

<div {condition && ...props}/>

But React doesn't seem to be allowing this, so is there another way?

1 Answers

You should wrap your expression and then use the spread syntax on the result of that expression:

<div {...(condition && props)}></div>

When the condition is false, the && operator evaluates to false. As a result, the spread syntax will end up spreading false which in object property spread is a no-op. When condition is true, the && evaluates to props, allowing you to spread your object properties.

Related