Sometimes, we want to conditionally pass prop to component inline with React.
In this article, we’ll look at how to conditionally pass prop to component inline with React.
How to conditionally pass prop to component inline with React?
To conditionally pass prop to component inline with React, we can use the spread and ternary operators.
For instance, we write
<Child
{...(this.props.editable ? { editable: this.props.editableOpts } : {})}
/>;
to set the props for Child
according to the value of this.props.editable
.
If it’s true
, then we spread the properties of { editable: this.props.editableOpts }
as its props.
Otherwise, we spread an empty object.
Conclusion
To conditionally pass prop to component inline with React, we can use the spread and ternary operators.