DEV Community

Muhammad Awais
Muhammad Awais

Posted on

Conditional Rendering in React

Another method for conditionally rendering elements inline is to use the JavaScript conditional operator

condition ? true : false
Enter fullscreen mode Exit fullscreen mode

In the example below, we use it to conditionally render the data coming in props with loading.

here, we have a loading variable having type boolean

const loading = false;
Enter fullscreen mode Exit fullscreen mode

so, we can render the data in a conditional way like this, !loading is responding as true. so Loading will be rendered.

{ !loading ? <p>Loading ...</p> : <p>{data}</p> }
Enter fullscreen mode Exit fullscreen mode

Whole, code will something like this,

import React from 'react';

const DemoConditional = function (props) {

    const { data } = props;
    const loading = false;

    return (
        <div>
            { !loading ? 
                <p>Loading ...</p> 
                : 
                <p>{data}</p> 
            }
        </div>
    );
};

export default DemoConditional;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)