Reputation: 2214
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?
Upvotes: 202
Views: 268702
Reputation: 2052
This (typescript) worked for me with React:
export function updateInputText(input: HTMLInputElement, value: string) {
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
input.constructor.prototype,
"value"
)!.set!;
nativeInputValueSetter.call(input, value);
const e = new Event("input", { bubbles: true });
input.dispatchEvent(e);
}
Upvotes: 2
Reputation: 6672
To trigger a React’s change
event handler registered on an input
element, you should set the value
property on the element using the native setter before dispatching the event (if you set the value
directly it will not work because it will use React’s overridden setter):
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
'value').set;
nativeInputValueSetter.call(input, newValue);
const event = new Event('input', { bubbles: true });
input.dispatchEvent(event);
Same solution for the textarea
element by substituting HTMLTextAreaElement
.
All credits go to this Cypress contributor and his solution.
To trigger a React’s change
event handler registered on an input
element, you should set the value
property on the element and set the simulated
property on the event (React specific) before dispatching the event:
input.value = newValue;
const event = new Event('input', { bubbles: true });
event.simulated = true;
input.dispatchEvent(event);
To understand why simulated
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 asset
s on the DOM nodevalue
prop (when you update the value via javascript). This has the side effect of meaning that if you update the input's value manuallyinput.value = 'foo'
then dispatch aChangeEvent
with{ target: input }
React will register both theset
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
set
s on theelement.value
. You can bail out of this logic secretly by tagging the event you trigger with asimulated
flag and react will always fire the event. https://github.com/jquense/react/blob/9a93af4411a8e880bbc05392ccf2b195c97502d1/src/renderers/dom/client/eventPlugins/ChangeEventPlugin.js#L128
Upvotes: 393
Reputation: 20614
A working solution can depend a bit on the implementation of the onChange
function you're trying to trigger. Something that worked for me was to reach into the react props attached to the DOM element and call the function directly.
I created a helper function to grab the react props since they're suffixed with a hash like .__reactProps$fdb7odfwyz
It's probably not the most robust but it's good to know it's an option.
function getReactProps(el) {
const keys = Object.keys(el);
const propKey = keys.find(key => key.includes('reactProps'));
return el[propKey];
}
const el = document.querySelector('XX');
getReactProps(el).onChange({ target: { value: id } });
Since the onChange function was only using target.value
I could pass a simple object to onChange
to trigger my change.
This method can also help with stubborn react owned DOM elements that are listing for onMouseDown
and do not respond to .click()
like you'd expect.
getReactProps(el).onMouseDown(new Event('click'));
Upvotes: 8
Reputation: 153
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 });
Upvotes: 8
Reputation: 1688
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);
Upvotes: 1
Reputation: 4178
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]);
Upvotes: 2
Reputation: 5363
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);
Upvotes: 9
Reputation: 1771
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)
}
}
Upvotes: 4
Reputation: 601
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);
}
};
Upvotes: 29
Reputation: 1274
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)} />
);
}
}
Upvotes: 0
Reputation: 1753
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
Upvotes: 3
Reputation: 1676
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
.
Upvotes: -1
Reputation: 1541
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' />
.
Upvotes: 21
Reputation: 1839
At least on text inputs, it appears that onChange
is listening for input events:
var event = new Event('input', { bubbles: true });
element.dispatchEvent(event);
Upvotes: 73
Reputation: 143194
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.
Upvotes: 9