Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 455
Qwerty Avatar asked Aug 13 '17 10:08

Qwerty


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.

like image 148
Dan Abramov Avatar answered Oct 20 '22 17:10

Dan Abramov