Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React showing 0 instead of nothing with short-circuit (&&) conditional component

I have the following simple short-circuit statement that should show either a component or nothing:

{profileTypesLoading && <GeneralLoader />}

If the statement is false, it renders a 0 instead of nothing.

I have done a console.log(profileTypesLoading) just to see quickly what the status of the profileTypesLoading property is and it's either 1 or 0 as expected. 0 should be false... causing nothing to render. Right?

Any idea why this would happen?

like image 470
Gurnzbot Avatar asked Oct 29 '18 14:10

Gurnzbot


People also ask

Why does React render 0?

If the statement is false, it renders a 0 instead of nothing.

How do you show nothing in React?

To return nothing from a React component, simply return null . When null is returned from a React component, nothing gets rendered.

What is empty <> In React?

The React framework offers a shorthand syntax for fragment components that appears as an empty tag: <></> . While it is supported in JSX syntax, it is not part of the HTML standard and thus is not supported natively by browsers.


1 Answers

Since your condition is falsy and so doesn't return the second argument (<GeneralLoader />), it will return profileTypesLoading, which is a number, so react will render it because React skips rendering for anything that is typeof boolean or undefined and will render anything that is typeof string or number:

To make it safe, you can either use a ternary expression {condition ? <Component /> : null} or boolean cast your condition like {!!condition && <Component />}

like image 70
enapupe Avatar answered Sep 23 '22 15:09

enapupe