Here is my code which is repeating pretty often, and I would like to avoid this:
{ isDataLoading ? (
<MyLoadingComponent />
) : !products ? (
<ThereIsNoDataComponent />
) : ( <div>Some text</div> )
}
How could I write this to avoid nested ternary operators?
Thanks guys
Cheers
One option is to make an IIFE:
{
(() => {
if (isDataLoading) return (<MyLoadingComponent />);
if (!products) return (<ThereIsNoDataComponent />);
return (<div>Some text</div>);
})()
}
Or, if you want to avoid re-creating the function every time:
const render = (isDataLoading, products) => {
if (isDataLoading) return (<MyLoadingComponent />);
if (!products) return (<ThereIsNoDataComponent />);
return (<div>Some text</div>);
};
and
{ render(isDataLoading, products) }