DEV Community

Cover image for React - Add props to component if matches the condition
Sandro Jhuliano Cagara
Sandro Jhuliano Cagara

Posted on • Updated on

React - Add props to component if matches the condition

When working with props and components, sometimes we need to send one specific property, when matches specific condition.

const 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

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

You can't use regular if/else conditions inside a component definition. Use Conditional (ternary) operator instead.

// if
{condition && (<span>Rendered when `truthy`</span>) }
Enter fullscreen mode Exit fullscreen mode
// unless
{condition || (<span>Rendered when `falsey`</span>) }
Enter fullscreen mode Exit fullscreen mode
// if-else
{condition ? (<span>Rendered when `truthy`</span>) : (<span>Rendered when `falsey`</span>)}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)