I have no idea why, but I was getting a load of 0
's being rendered on the page. Finally I narrowed it down to a zero/ 0
that I wasn't forcing to be a boolean. React will not render any other digit other than 0
https://codesandbox.io/s/pyk11w5y5j
Why does 0
render but 10
for example, does not render?
function App() {
const weirdOh = -0;
const testParam = true;
return (
<div className="App">
{testParam && weirdOh && <h1>Will Show</h1>}
<h2>Start editing to see some magic happen!</h2>
</div>
);
}
Fix
{testParam && !!weirdOh && <h1>Will SHow</h1>}
Numbers are perfectly valid values in react, and 0
is just that, a number.
Make sure to convert it to a boolean to avoid this, since false
doesn't render anything:
{testParam && !!weirdOh && <h1>Will Show</h1>}
or
{testParam && weirdOh !== 0 && <h1>Will Show</h1>}
If you set weirdOh
to a non-zero number, then it won't be falsy, and your <h1>
will be returned from the expression and be rendered.
This is not related to react, but simply how &&
in JS works:
(1 && 'test') === 'test'
because after a truthy value, you go to the next one in the chain (0 && 'test') === 0
because as soon as you hit a falsy value, that value is used
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.