I have a group of props that I need to apply to a ponent 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 ponent:
<div {condition && ...props}/>
But React doesn't seem to be allowing this, so is there another way?
I have a group of props that I need to apply to a ponent 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 ponent:
<div {condition && ...props}/>
But React doesn't seem to be allowing this, so is there another way?
Share Improve this question edited Jun 14, 2021 at 4:17 Moaaz Bhnas asked Jun 13, 2021 at 11:46 Moaaz BhnasMoaaz Bhnas 1,1707 gold badges20 silver badges41 bronze badges 01 Answer
Reset to default 15You 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.