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

Gurnzbot picture Gurnzbot · Oct 29, 2018 · Viewed 11k times · Source

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?

Answer

enapupe picture enapupe · Oct 29, 2018

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 />}