DEV Community

Luis Puentes Vega
Luis Puentes Vega

Posted on

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)