Skip to content

Loosen up type requirements for event handlers #11027

@jeffijoe

Description

@jeffijoe

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

Feature

What is the current behavior?

When adding event handlers, it is common practice to do something like:

const MyButton = ({ canClick, onClick }) =>
  <div onClick={canClick && onClick}></div>

This was fine in React 15.x, but in 16 it reports a warning, which is technically correct:

Expected onClick listener to be a function, instead got a value of boolean type.

However, this now forces you to use the more verbose variant:

const MyButton = ({ canClick, onClick }) =>
  <div onClick={(canClick && onClick) ? onClick : undefined}></div>

What is the expected behavior?

I think it makes sense to allow null, false, and undefined in addition to function types for event handlers. Or just anything "falsy", although that may be too much to ask.

I definitely understand the rationale from a type safety perspective, but this does make it less pragmatic. I am personally a huge fan of how JS evaluates null, 0, "" and undefined to false, and it reduces the amount of boilerplate needed to conditionally wire up handlers.

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

React 16, all browsers. This did not emit a warning in React 15 and below.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions