-1

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>}
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
Jamie Hutber
  • 26,790
  • 46
  • 179
  • 291

1 Answers1

3

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
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • Why they, does `10` not render? This is also a digit? – Jamie Hutber Mar 27 '19 at 13:05
  • 1
    Because that's truthy, so your `

    ` will be returned from the expression.

    – ThiefMaster Mar 27 '19 at 13:06
  • Interesting, so because `0` is falsy it renders? I don't really understand why this renders just because it is falsey. – Jamie Hutber Mar 27 '19 at 13:07
  • I understand that it is part of the expression, and being false means the `

    ` doesn't render, but I can't bridge the cap to understanding why it renders.

    – Jamie Hutber Mar 27 '19 at 13:10
  • Maybe you should be explaining how `testParam && weirdOh &&

    Will Show

    ` works to add more value to your answer
    – Shubham Khatri Mar 27 '19 at 13:10
  • 1
    a `&&` chain stops as soon as something falsy is reached, and will return that element. if no values are falsy, the last one is returned. `1 && 'test' === 'test'` but ` && 'test' === 0` – ThiefMaster Mar 27 '19 at 13:10
  • Ah but of course... and any higher digit is truthy, hence why converting to a boolean it will cancel the chain and render nothing. Aka nothing to do with react – Jamie Hutber Mar 27 '19 at 13:11