In this article we will discuss how to add or pass a component prop based on a condition.
Lets have a component named MyButtonComponent that takes a prop name
<MyButtonComponent name="some text" />
Now I need to pass this prop based on a flag called hasName of type Boolean
We can do this using the spread operator
<MyButtonComponent {...(hasName ? {name: "some text"} : {} )} />
What are we doing?
We are using spread operator to spread the object {name: “some text”} or an empty object {} based on the value of our flag hasName. To check the condition we are using ternary operator. So the component have name prop or no prop named name
Hope it helps, happy coding…