Always_a_learner
Always_a_learner

Reputation: 5055

React Js conditional rendering of html element not working as expected

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.

Upvotes: 1

Views: 2188

Answers (3)

Jan-Philipp Marks
Jan-Philipp Marks

Reputation: 1539

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

Upvotes: 1

Valentin
Valentin

Reputation: 11792

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

Upvotes: 1

Nicolae Maties
Nicolae Maties

Reputation: 2655

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

Upvotes: 1

Related Questions