What is the best way to trigger change or input event in react js

For React 16 and React >=15.6

Setter .value= is not working as we wanted because React library overrides input value setter but we can call the function directly on the input as context.

var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
nativeInputValueSetter.call(input, 'react 16 value');

var ev2 = new Event('input', { bubbles: true});

For textarea element you should use prototype of HTMLTextAreaElement class.

New codepen example.

All credits to this contributor and his solution

Outdated answer only for React <=15.5

With react-dom ^15.6.0 you can use simulated flag on the event object for the event to pass through

var ev = new Event('input', { bubbles: true});
ev.simulated = true;
element.value="Something new";

I made a codepen with an example

To understand why new flag is needed I found this comment very helpful:

The input logic in React now dedupe’s change events so they don’t fire
more than once per value. It listens for both browser onChange/onInput
events as well as sets on the DOM node value prop (when you update the
value via javascript). This has the side effect of meaning that if you
update the input’s value manually input.value=”foo” then dispatch a
ChangeEvent with { target: input } React will register both the set
and the event, see it’s value is still `’foo’, consider it a duplicate
event and swallow it.

This works fine in normal cases because a “real” browser initiated
event doesn’t trigger sets on the element.value. You can bail out of
this logic secretly by tagging the event you trigger with a simulated
flag and react will always fire the event.

Leave a Comment