Home > Blockchain >  NaN still pass boolean condition in React
NaN still pass boolean condition in React

Time:12-16

I want to show value when only it's value is exact number. So added condition like under. But when values is NaN, it still passes condition. Possible type of value is number | null | undefined. Following is my code.

{value ? <p>{value} people are waiting.</p> : <Skeleton />}

I also tried

{value && !isNaN(value) ? <p>{value} people are waiting.</p> : <Skeleton />}
{value && value !== "NaN" ? <p>{value} people are waiting.</p> : <Skeleton />}

But result is NaN people are waiting. by passing condition. How can I fix this problem? Thanks.

CodePudding user response:

You can use Number() instead of isNaN it will work fine with your ternary. But I guess you would want to render <p>{value} people are waiting.</p> if your value in not NaN so modify your condition accordingly.

 {value && Number(value) ?  <p>{value} people are waiting.</p> :<Skeleton /> }

CodePudding user response:

Shouldn't it be:

{value && !isNaN(value) ? <p>{value} people are waiting.</p> : <Skeleton />}

Looks like it was turned around?

CodePudding user response:

Assuming you want to show Skeleton when it is not an exact number and your string when it is you could use:

{Number(value) ? <p>{value} people are waiting.</p> : <Skeleton />}

This solution should cover most scenarios however; it is possible to end up with:

"-1 people are waiting."

To avoid that you could do:

{value > 0 ? <p>{value} people are waiting.</p> : <Skeleton />}

When you try to compare against 0, javascript will implicitly try to use value as a number, if that fails, the condition will also fail.

EDIT: I lied! The value true will also pass this condition:

['string', //false
 '12', //true
 '0', //false
 'c', //false
 1, //true
 2, //true
 false, //false
 true, //true --> !
 null, //false
 (1/"test"), //false
 -1 //false
].forEach(value => {
    console.log(
        value > 0
    );
});
  • Related