input with onClick handler in React?



Since change events are fired for input in some browsers only (namely IE) only when the focus is lost, my understanding is that the click event is a better way to listen for changes (see Getting value of HTML Checkbox from onclick/onchange events

However, when I only supply only the checked property with an onClick handler to a controlled input element in react, it complains with:

Warning: Failed prop type: You provided a `checked` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultChecked`. Otherwise, set either `onChange` or `readOnly`.

What is the solution here? The react documentation seems to suggest using onChange, but that conflicts with the recommendations in the answer listed above.


React provides a cross-browser wrapper called SyntheticEvent to provide a normalized interface to events, but the documentation doesn’t explicitly state which cases are or are not handled. Regarding the edge case with IE, this Github comment from 2015 suggests that it’s already handled:

… react uses the native click event to listen to user interaction with the radio, and then calls the onchange for the input. The reason for this (at least according to the comment in the code) is because IE8 does not fire the change event until blur, so in order to be ‘compatible’ with IE8, the click event is used.

Looking at React’s source, to me it strongly looks like this indeed is the case:

function shouldUseClickEvent(elem) {
  // Use the `click` event to detect changes to checkbox and radio inputs.
  // This approach works across all browsers, whereas `change` does not fire
  // until `blur` in IE8.
  const nodeName = elem.nodeName;
  return (
    nodeName &&
    nodeName.toLowerCase() === 'input' &&
    (elem.type === 'checkbox' || elem.type === 'radio')

So I would just use onChange like you would on a modern browser, and worry about doing it yourself (or even opening a new issue in React’s repo) if you find the behavior to differ on IE.

Answered By – cbr

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More