DEV Community

Luis Puentes Vega
Luis Puentes Vega

Posted on

5 2

React - Add prop to component if matches specific condition

When working with components, sometimes we need to send one specific property just when matches specific condition as an example:

function MyComponent = () => {
  return (
   <Select 
    label="Countries"
    options={}
    required
   />
  );
}
Enter fullscreen mode Exit fullscreen mode

if we want to send required just when matches specific conditions, we can spread the properties

function MyComponent = () => {
  return (
   <Select 
    label="Countries"
    options={}
    {...(shouldBeRequired && { required })}
   />
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay