How to Conditionally Add Props to a React Component?

For the purpose of this article, let's suppose we wanted to create a Link component that would conditionally add rel="noopener" attribute if the target prop had the value _blank. To illustrate this, let's consider the following two cases:

ReactDOM.render(
    <Link href="https://google.com" target="_blank">Google</Link>,
    document.getElementById('app')
);

// expected output: <a href="https://google.com" rel="noopener" target="_blank">Google</a>
ReactDOM.render(
    <Link href="foo.html" target="_self">Foo</Link>,
    document.getElementById('app')
);

// expected output: <a href="foo.html" target="_self">Foo</a>

Now, let's see all the different ways we can conditionally add props in our react component:

Using Inline Ternary Operator

Setting a property/attribute value as undefined or null does not show that property in the DOM. We can use that with the ternary operator to conditionally add a property like so:

<MyComponent prop={condition ? 'value' : undefined} />

For example:

function Link({ href, target, children }) {
    return (
        <a
            href={href}
            rel={target === '_blank' ? 'noopener' : undefined}
        >
            {children}
        </a>
    );
}

Using the Spread Operator

You could prepare your props object in different ways and then use the spread operator to add those properties to a component.

An important thing to remember is that the properties that appear to the right overwrite the properties of the same name to their left. So, if the spread has properties of the same name before it, it would overwrite them, and if there are properties of the same name after it, then the spread props/values will be overwritten.

Spreading Object Properties:

Create an object with all the props you wish to add to your react component (including the properties you wish to add conditionally). Then you could simply use the spread operator to add these props to the component. For example:

const props = { title: 'bar' };

function Link({ href, target, children }) {
    if (target === '_blank') {
        props.rel = 'noopener';
    }

    return <a href={href} { ...props }>{children}</a>;
}

Conditionally Spreading the Object Properties:

We could use the logical && or the ternary operator, along with the spread operator, to conditionally add props to a component like so:

function Link({ href, target, children }) {
    const condition = target === '_blank';

    const props = {
        href,
        // using the ternary operator:
        ...( condition ? { title: 'Opens in new tab' } : {} ),
        // using the logical && operator:
        ...( condition && { rel: 'noopener' } ),
    };

    return <a { ...props }>{children}</a>;
}

Or, alternatively, you could do the same inline like so:

function Link({ href, target, children }) {
    const condition = target === '_blank';

    return (
        <a
            href={href}
            // using the ternary operator:
            { ...( condition ? { title: 'Opens in new tab' } : {} ) }
            // using the logical && operator:
            { ...( condition && { rel: 'noopener' } ) }
        >
            {children}
        </a>
    );
}

The syntax with logical && operator works because the transpiler (such as babel) evaluates the condition but does not expand when it encounters boolean false (as the spread operator only accepts iterables). If this doesn't work for you as expected, then you can always use the ternary operator syntax instead.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.