Another method for conditionally rendering elements inline is to use the JavaScript conditional operator
condition ? true : false
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;
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> }
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;
Top comments (0)