What is the best way to trigger onchange event in react js

Reactjs

Reactjs Problem Overview


We use Backbone + ReactJS bundle to build a client-side app. Heavily relying on notorious valueLink we propagate values directly to the model via own wrapper that supports ReactJS interface for two way binding.

Now we faced the problem:

We have jquery.mask.js plugin which formats input value programmatically thus it doesn't fire React events. All this leads to situation when model receives unformatted values from user input and misses formatted ones from plugin.

It seems that React has plenty of event handling strategies depending on browser. Is there any common way to trigger change event for particular DOM element so that React will hear it?

Reactjs Solutions


Solution 1 - Reactjs

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});
input.dispatchEvent(ev2);

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';
element.dispatchEvent(ev);

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. > https://github.com/jquense/react/blob/9a93af4411a8e880bbc05392ccf2b195c97502d1/src/renderers/dom/client/eventPlugins/ChangeEventPlugin.js#L128

Solution 2 - Reactjs

At least on text inputs, it appears that onChange is listening for input events:

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

Solution 3 - Reactjs

I know this answer comes a little late but I recently faced a similar problem. I wanted to trigger an event on a nested component. I had a list with radio and check box type widgets (they were divs that behaved like checkboxes and/or radio buttons) and in some other place in the application, if someone closed a toolbox, I needed to uncheck one.

I found a pretty simple solution, not sure if this is best practice but it works.

var event = new MouseEvent('click', {
 'view': window, 
 'bubbles': true, 
 'cancelable': false
});
var node = document.getElementById('nodeMyComponentsEventIsConnectedTo');
node.dispatchEvent(event);

This triggered the click event on the domNode and my handler attached via react was indeed called so it behaves like I would expect if someone clicked on the element. I have not tested onChange but it should work, and not sure how this will fair in really old versions of IE but I believe the MouseEvent is supported in at least IE9 and up.

I eventually moved away from this for my particular use case because my component was very small (only a part of my application used react since i'm still learning it) and I could achieve the same thing another way without getting references to dom nodes.

UPDATE:

As others have stated in the comments, it is better to use this.refs.refname to get a reference to a dom node. In this case, refname is the ref you attached to your component via <MyComponent ref='refname' />.

Solution 4 - Reactjs

Expanding on the answer from Grin/Dan Abramov, this works across multiple input types. Tested in React >= 15.5

const inputTypes = [
	window.HTMLInputElement,
	window.HTMLSelectElement,
	window.HTMLTextAreaElement,
];

export const triggerInputChange = (node, value = '') => {

	// only process the change on elements we know have a value setter in their constructor
	if ( inputTypes.indexOf(node.__proto__.constructor) >-1 ) {

		const setValue = Object.getOwnPropertyDescriptor(node.__proto__, 'value').set;
		const event = new Event('input', { bubbles: true });

		setValue.call(node, value);
		node.dispatchEvent(event);

	}

};

Solution 5 - Reactjs

You can simulate events using ReactTestUtils but that's designed for unit testing.

I'd recommend not using valueLink for this case and simply listening to change events fired by the plugin and updating the input's state in response. The two-way binding utils more as a demo than anything else; they're included in addons only to emphasize the fact that pure two-way binding isn't appropriate for most applications and that you usually need more application logic to describe the interactions in your app.

Solution 6 - Reactjs

Triggering change events on arbitrary elements creates dependencies between components which are hard to reason about. It's better to stick with React's one-way data flow.

There is no simple snippet to trigger React's change event. The logic is implemented in ChangeEventPlugin.js and there are different code branches for different input types and browsers. Moreover, the implementation details vary across versions of React.

I have built react-trigger-change that does the thing, but it is intended to be used for testing, not as a production dependency:

let node;
ReactDOM.render(
  <input
    onChange={() => console.log('changed')}
    ref={(input) => { node = input; }}
  />,
  mountNode
);

reactTriggerChange(node); // 'changed' is logged

CodePen

Solution 7 - Reactjs

I found this on React's Github issues: Works like a charm (v15.6.2)

Here is how I implemented to a Text input:

changeInputValue = newValue => {

    const e = new Event('input', { bubbles: true })
    const input = document.querySelector('input[name=' + this.props.name + ']')
    console.log('input', input)
    this.setNativeValue(input, newValue)
    input.dispatchEvent(e)
  }

  setNativeValue (element, value) {
    const valueSetter = Object.getOwnPropertyDescriptor(element, 'value').set
    const prototype = Object.getPrototypeOf(element)
    const prototypeValueSetter = Object.getOwnPropertyDescriptor(
      prototype,
      'value'
    ).set

    if (valueSetter && valueSetter !== prototypeValueSetter) {
      prototypeValueSetter.call(element, value)
    } else {
      valueSetter.call(element, value)
    }
  }

Solution 8 - Reactjs

For HTMLSelectElement, i.e. <select>

var element = document.getElementById("element-id");
var trigger = Object.getOwnPropertyDescriptor(
  window.HTMLSelectElement.prototype,
  "value"
).set;
trigger.call(element, 4); // 4 is the select option's value we want to set
var event = new Event("change", { bubbles: true });
element.dispatchEvent(event);

Solution 9 - Reactjs

well since we use functions to handle an onchange event, we can do it like this:

class Form extends Component {
 constructor(props) {
  super(props);
  this.handlePasswordChange = this.handlePasswordChange.bind(this);
  this.state = { password: '' }
 }

 aForceChange() {
  // something happened and a passwordChange
  // needs to be triggered!!

  // simple, just call the onChange handler
  this.handlePasswordChange('my password');
 }

 handlePasswordChange(value) {
 // do something
 }

 render() {
  return (
   <input type="text" value={this.state.password} onChange={changeEvent => this.handlePasswordChange(changeEvent.target.value)} />
  );
 }
}

Solution 10 - Reactjs

The Event type input did not work for me on <select> but changing it to change works

useEffect(() => {
    var event = new Event('change', { bubbles: true });
	selectRef.current.dispatchEvent(event); // ref to the select control
}, [props.items]);

Solution 11 - Reactjs

This ugly solution is what worked for me:

let ev = new CustomEvent('change', { bubbles: true });
Object.defineProperty(ev, 'target', {writable: false, value: inpt });
Object.defineProperty(ev, 'currentTarget', {writable: false, value: inpt });
const rHandle = Object.keys(inpt).find(k => k.startsWith("__reactEventHandlers"))
inpt[rHandle].onChange(ev);

Solution 12 - Reactjs

I stumbled upon the same issue today. While there is default support for the 'click', 'focus', 'blur' events out of the box in JavaScript, other useful events such as 'change', 'input' are not implemented (yet).

I came up with this generic solution and refactored the code based on the accepted answers.

export const triggerNativeEventFor = (elm, { event, ...valueObj }) => {
  if (!(elm instanceof Element)) {
    throw new Error(`Expected an Element but received ${elm} instead!`);
  }

  const [prop, value] = Object.entries(valueObj)[0] ?? [];
  const desc = Object.getOwnPropertyDescriptor(elm.__proto__, prop);

  desc?.set?.call(elm, value);
  elm.dispatchEvent(new Event(event, { bubbles: true }));
};

How does it work?

triggerNativeEventFor(inputRef.current, { event: 'input', value: '' });

Any 2nd property you pass after the 'event' key-value pair, it will be taken into account and the rest will be ignored/discarded. This is purposedfully written like this in order not to clutter arguments definition of the helper function. The reason as to why not default to get descriptor for 'value' only is that for instance, if you have a native checkbox <input type="checkbox" />, than it doesn't have a value rather a 'checked' prop/attribute. Then you can pass your desired check state as follows:

triggerNativeEventFor(checkBoxRef.current, { event: 'input', checked: false });

Solution 13 - Reactjs

If you are using Backbone and React, I'd recommend one of the following,

They both help integrate Backbone models and collections with React views. You can use Backbone events just like you do with Backbone views. I've dabbled in both and didn't see much of a difference except one is a mixin and the other changes React.createClass to React.createBackboneClass.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwalliceView Question on Stackoverflow
Solution 1 - ReactjsGrinView Answer on Stackoverflow
Solution 2 - ReactjsMichaelView Answer on Stackoverflow
Solution 3 - ReactjsRobert-WView Answer on Stackoverflow
Solution 4 - ReactjscjpeteView Answer on Stackoverflow
Solution 5 - ReactjsSophie AlpertView Answer on Stackoverflow
Solution 6 - ReactjsVitaly KuznetsovView Answer on Stackoverflow
Solution 7 - Reactjsa2ron44View Answer on Stackoverflow
Solution 8 - ReactjsComputer's GuyView Answer on Stackoverflow
Solution 9 - ReactjsaprilmintacpinedaView Answer on Stackoverflow
Solution 10 - ReactjsShashank ShekharView Answer on Stackoverflow
Solution 11 - Reactjsuser5480949View Answer on Stackoverflow
Solution 12 - ReactjsAlban NurkollariView Answer on Stackoverflow
Solution 13 - ReactjsBlaine HatabView Answer on Stackoverflow