React: Bug in conditional rendering(&&)

Created on 9 May 2019  路  3Comments  路  Source: facebook/react

Do you want to request a feature or report a bug?

bug

What is the current behavior?

Conditional Rendering (&&)

  1. list length value is zero(0).
  2. zero(0) is falsy from javascript.
  3. However, zero(0) is output as the rendered result.

If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem. Your bug will get fixed much faster if we can run your code and it doesn't have dependencies other than React. Paste the link to your JSFiddle (https://jsfiddle.net/Luktwrdm/) or CodeSandbox (https://codesandbox.io/s/new) example below:

JSFiddle: example

What is the expected behavior?

zero(0) is not output.

Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?

React v16.8.6
Chrome browser(v73.0.3683.103)

Most helpful comment

are you sure what it is a bug ? :)
I guess it's even not related to react. From prospective of javascript its absolutely right behavior.

<--node repl-->

> 0 && 'xxx'
0
> false && 'xxx'
false
> true && 'xxx'
'xxx'

if you wanna achieve correct behavior, try to convert type to boolean.
Boolean(0) && 'xxx'
or short form
!!0 && 'xxx'

All 3 comments

I believe it is by design

The bug is that this renders 0 when unreadMessages.length is 0

{unreadMessages.length &&
  <h2>
    You have {unreadMessages.length} unread messages.
  </h2>
}

This is an expression that resolves to 0 when length is 0

You could easily fix it with unreadMessages.length > 0

What if you want to render the length by some condition?

e.g.

{displayLength && unreadMessages.length} resolves to {unreadMessages.length} if displayLength is truthy

Then developers would report bugs that it does NOT render the result when the unreadMessages.length is 0.

are you sure what it is a bug ? :)
I guess it's even not related to react. From prospective of javascript its absolutely right behavior.

<--node repl-->

> 0 && 'xxx'
0
> false && 'xxx'
false
> true && 'xxx'
'xxx'

if you wanna achieve correct behavior, try to convert type to boolean.
Boolean(0) && 'xxx'
or short form
!!0 && 'xxx'

are you sure what it is a bug ? :)
I guess it's even not related to react. From prospective of javascript its absolutely right behavior.

<--node repl-->

> 0 && 'xxx'
0
> false && 'xxx'
false
> true && 'xxx'
'xxx'

if you wanna achieve correct behavior, try to convert type to boolean.
Boolean(0) && 'xxx'
or short form
!!0 && 'xxx'

@kunukn @Yauheni-blr

Thank you for answer.

I thought && in JSX differs from && in Javascript.

I knew this was not a bug!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

trusktr picture trusktr  路  3Comments

zpao picture zpao  路  3Comments

zpao picture zpao  路  3Comments

krave1986 picture krave1986  路  3Comments

UnbearableBear picture UnbearableBear  路  3Comments