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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay