Add component prop based on condition
ReactJS

Add component prop based on condition in ReactJS

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…

🍺

Computer engineer interested in programming, electronics, application architecture, data visualization, automation and performance optimization.

Leave a Reply