Source:  Twitter logo

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 });

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.

Please see this answer that describes the solution:

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

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

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

15 users liked answer #0dislike answer #015
Dan Abramov profile pic
Dan Abramov

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).