Do you want to request a feature or report a bug?
Bug
What is the current behavior?
Triggering a native DOM 'input' event, does not trigger the onChange handler in React DOM versions 15.6 and above.
If the current behavior is a bug, please provide the steps to reproduce and if possible a minimal demo of the problem via https://jsfiddle.net or similar (template for React 16: https://jsfiddle.net/Luktwrdm/, template for React 15: https://jsfiddle.net/hmbg7e9w/).
React DOM v15.5: https://jsfiddle.net/6s0tbdab/2/
React DOM v16: https://jsfiddle.net/5jgd6zn6/1/
Note that the 'alert' only appears on the 15.5 fiddle.
What is the expected behavior?
I would expect the onChange handler to be fired. I'm not sure if this is the correct approach, and so happy to discuss other options here.
Which versions of React, and which browser / OS are affected by this issue? Did this work in previous versions of React?
See above fiddles. Chrome on OSX, for example.
cc @jquense I keep forgetting—what's the recommendation for this case?
I don't know what the proper recommended way to do it is, but we do it this way in tests: https://jsfiddle.net/5jgd6zn6/2/
We should probably expose a helper maybe for this...depends on the use case tho i guess. I think generally when trying to get "underneath" react's event system the answer may just be "Here be Dragons"?
I think having to do this:
const setValue = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
const event = new Event('input', { bubbles: true });
setValue.call(node, 'Test');
node.dispatchEvent(event);
is not too bad. Just need to make sure it's documented somewhere and is easy to find.
I think we can count this as “documented”. (One of first google answers for "trigger input change event react").
So I'll close this.
Thanks @gaearon @jquense.
I've updated the fiddles with my working solution:
React v15.5: https://jsfiddle.net/6s0tbdab/4/
React v16^: https://jsfiddle.net/hpp0wLkv/2/
Also added some more detail to stack overflow: https://stackoverflow.com/questions/23892547/what-is-the-best-way-to-trigger-onchange-event-in-react-js/47409362#47409362
@gaearon @jquense do you have a way of doing this with
React 16.2: https://jsfiddle.net/vuea4bsL/3/
Most helpful comment
I think having to do this:
is not too bad. Just need to make sure it's documented somewhere and is easy to find.