1

I am adding conditions to display a div element and condition has a variable which comes to be 0 and when it is 0 then 0 displays instead of not displaying anything.

using functional component:

return (
  <div>
    {flag1 && flag2 &&  data1 && data1.length && data2 && data2.length &&  (
      <div className="answers-heading">Answers ({data2.length})</div>
    )}
  </div>
);

In the above code, I expect if any of the variables are not true then it should simply not display div element but I am getting 0 in UI. When all conditions true then it works fine. I have created stackblitz demo to show how it is working in an unexpected manner.

Any help would be appreciated.

Already spent a whole day debugging but could not find the reason.

glinda93
  • 7,659
  • 5
  • 40
  • 78
Always_a_learner
  • 4,585
  • 13
  • 63
  • 112

3 Answers3

1
return (
  <div>
    {flag1 && flag2 &&  data1 && data1.length && data2 && data2.length ?  (
      <div className="answers-heading">Answers ({data2.length})</div>
    ) : null}
  </div>
);

You should start using ternary instead of only && operator, you will end up with divs with 0 rendered inside. You get 0 because of && operator check which is basically indicating that your condition is "falsey".

Btw, your condition looks fine, you should put that into a const too.

This might help you out too: React showing 0 instead of nothing with short-circuit (&&) conditional component

glinda93
  • 7,659
  • 5
  • 40
  • 78
Nicolae Maties
  • 2,476
  • 1
  • 16
  • 26
1

Your issue comes from the fact that data1.length or data2.length is equal to 0. It makes your condition resolve to 0 because true && 0 === 0.

If you want to avoid this, you may change your code to:

return (
  <div>
    {flag1 && flag2 && data1 && data1.length !== 0 && data2 && data2.length !== 0 && (
      <div className="answers-heading">Answers ({data2.length})</div>
    )}
  </div>
);
Valentin
  • 10,769
  • 2
  • 17
  • 27
1

Put !! Infront of all numeric values and it will be true if that number exists and is not 0

Jan-Philipp Marks
  • 1,419
  • 8
  • 13