0

in my nextjs app, when the page loads there is a 0 in the top left corner for a split second. In that page, I get some data from Sanity CMS with getStaticProps and return the content.. I notice that even if I return a empty fraction the 0 appears.

  return <>{Object?.keys(finalContent).length && <></>}</>;

If I return just the empty fraction without checking for

Object?.keys(finalContent).length && 

the 0 is gone

  return <></>;  // no 0 in the page

Anyone know how to remove it?

enter image description here

user16469315
  • 89
  • 1
  • 1
  • 9
  • Does this answer your question? [React showing 0 instead of nothing with short-circuit (&&) conditional component](https://stackoverflow.com/questions/53048037/react-showing-0-instead-of-nothing-with-short-circuit-conditional-component) – juliomalves Dec 22 '21 at 14:59

1 Answers1

2

I assume with Object?.keys(finalContent).length you want to ensure that the data was successfully fetched.

As a background, JS has short-circuit evaluation, meaning:

  • 0 && 3 gets evaluated as 0
  • 3 || 0 gets evaluated as 3
  • Analogically, if Object?.keys(finalContent).length is 0, it would be equivalent the expression 0 && x which gets evaluated as 0

And in React.js, the 0 is the only falsy value that actually renders (null, undefined, and "" do not get rendered)

Therefore, a 0 is rendered to your screen when the length of the data array is 0.

The perhaps easiest solution would be turning the falsy length of 0 into an a boolean false and all other truthy lenghts >0 into true like that: !!(Object?.keys(finalContent).length)

Final solution:

    return <>{!!(Object?.keys(finalContent).length) && <></>}</>;

Now, if Object?.keys(finalContent).length is 0, it gets turned into a false, which will not be rendered by React.

maxeth
  • 1,315
  • 1
  • 8
  • 17