Moaaz Bhnas
Moaaz Bhnas

Reputation: 1170

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

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?

Upvotes: 10

Views: 5242

Answers (1)

Nick Parsons
Nick Parsons

Reputation: 50684

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

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

Where props is an object like you described:

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

When the condition is false, the && operator evaluates to false. As a result, React calls React.createElement(type, props, ...children) with a second argument of false, leaving the props untouched. When condition is true, the && evaluates to the props object, allowing you to merge your object's properties.

Upvotes: 15

Related Questions