React: Input onChange won't fire if you attach an event listener with a callback function

Created on 2 Jan 2019  路  2Comments  路  Source: facebook/react

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

What is the current behavior?
React JS won't fire the onChange event on inputs when you add an Event Listener passing a callback function.

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:

https://codesandbox.io/s/8wxkrynpl

What is the expected behavior?
input onChange to fire even if you attach an event listener to the dom passing a callback function

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

I am using React 16.7, I have tested only on chrome since at the company I don't have access to any other browser.

Most helpful comment

The issue isn't that you're passing a callback, it's that you're calling preventDefault. The change event happens as a result of the keydown event, so preventing the default behavior stops that from happening. The same would happen if you just passed onKeyDown to the input element instead of using window.addEventListener.

All 2 comments

The issue isn't that you're passing a callback, it's that you're calling preventDefault. The change event happens as a result of the keydown event, so preventing the default behavior stops that from happening. The same would happen if you just passed onKeyDown to the input element instead of using window.addEventListener.

What @heyimalex said and also you want to write your onChange listeners like this when you're passing an event
onChange={e => this.handleChange(e)}
Try it now :)
https://codesandbox.io/s/pjz09n6kr7

Was this page helpful?
0 / 5 - 0 ratings