8

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.

Qwerty
  • 323
  • 1
  • 6
  • 33
  • This is not React, but imperative programming. You either need to change props or state to re-render the form. – lukaleli Aug 13 '17 at 11:00
  • The form I'm trying to programtically is definitely using React. The answer's last comment here seems to say this is not working in the specific version of React, https://stackoverflow.com/a/31056122/1127547 So what would be the alternative? How can I change the props (i'm already changing the value property of the input field) or state to re-render the form? – Qwerty Aug 13 '17 at 11:29
  • use `setState`. or simply just watch any basic tutorial on React that will explain things to you. – Denialos Aug 13 '17 at 11:38
  • 1
    But I'm not to use React when programmatically changing the input value and triggering the event. Is it possible to use setState method totally outside React? How do you trigger the event independent of React for a React based form. – Qwerty Aug 13 '17 at 23:13
  • I know it's not the right way but it works. `import ReactTestUtils from 'react-dom/test-utils'; const element = document.activeElement; ReactTestUtils.Simulate.change(element);` – Nobuhito Kurose Aug 15 '17 at 03:44
  • The above will probably not work because of dead code elimination in production enviromnents. Check the following: https://www.npmjs.com/package/react-trigger-change – Gie Spaepen Oct 02 '17 at 15:31

1 Answers1

16

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.

Dan Abramov
  • 264,556
  • 84
  • 409
  • 511