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.

2
  • 1
    If flag1 or flag2 are of type number, it is expected. You should use boolean type for these if they are really flags with only 2 useful values. Commented Jul 23, 2020 at 12:36
  • @Valentin flag1 and flag2 are boolean. In demo, I kept them false. Commented Jul 23, 2020 at 13:07

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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>
);

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.