Sven Sven - 1 year ago 127
React JSX Question

JSX doesn't evaluate integer in expression as boolean

I'm used to write render optional Components like this:

var Foo = React.createClass({
render: function() {
var length = 0;
return <div>Foo {length && <Bar />}</div>;

This shorthand
is mentioned in the if/else in JSX guide as immediately-invoked function expression. However, since my latest update of React, it started to render
instead of

Here is a jsfiddle

Why is that happening?

Answer Source

The && operator evaluates the left-hand expression first, and if the left-hand expression evaluates to something falsy it returns the value of the left-hand expression without evaluating further.

So (0 && "Bar") evaluates to 0 which is then rendered as a string. If all falsy values were discarded in the rendering then there would be no way to print a 0 in React, for example length is { 0 } would only print length is.

However false, null and undefined are discarded by React renderer if used as a child, and it's exactly for this use case:

length is { 0 } // length is 0
length is { NaN} // length is NaN
length is { null } // length is
length is { false } // length is
length is { undefined } // length is

You need the left-hand expression of your && operator to return one of those three, the simplest being a boolean:

( !!length && "Bar" ) // evaluates to false, doesn't print
( (length > 0) && "Bar" ) // evaluates to false, doesn't print
( (length != 0) && "Bar" ) // evaluates to false, doesn't print
( Boolean(length) && "Bar" ) // evaluates to false, doesn't print
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download