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

Oldest comments (0)

Classic DEV Post from 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!