Trigger change events when the value of an input changed programmatically React

Viewed 7308

If a form is using React JS based interface, and the input field value is changed programatically, how do you trigger the value change event programatically?

I understand DOM input event is translated to synthetic change event in React. So this used to work on the input element, it used to enable the button in the form after entering the input value programatically.

var event = new Event('input', { bubbles: true });
inputElement.dispatchEvent(event);

But does not work anymore possibly because of the updated version of React JS used. Any reason why this does not work? And what is the alternative now? I have even tried to trigger events like change, focus, blur events but none of them worked. Also tried to change the value attribute instead of say

inputElement.value = "test";

But still the above dispatch of the event is not working.

1 Answers

Please see this answer that describes the solution:

var setValue = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value').set;
setValue.call(input, 'my new value');

var e = new Event('input', { bubbles: true });
input.dispatchEvent(e);

This would only work for input tags; for textarea you'll want HTMLTextAreaElement instead.

Related