I have a simple React component:
state = {
value: '',
};
render() {
return <select onChange={this.handleChange} value={this.state.value}>
<option value="">--</option>
<option value="1">One</option>
</select>;
}
handleChange = (e) => {
this.setState({
value: e.target.value,
});
console.log('Handling Change!!')
};
I want to be able to trigger the event handler programmatically via ordinary javascript or, in this example, jQuery.
$select = $('select');
$select.val('1');
// then
$select.trigger('change');
// or
$select.trigger('input');
But none of these trigger the onChange
handler in the React component, and therefore the state doesn't get updated.
My question: How can I trigger the onChange
handler using the DOM and Javascript?
[edit]
To clarify a bit further, I am mounting the React Component like this:
el = document.createElement('div')
ReactDOM.render(MySelect, el)
$select = $(el).find('select');
$select.val('1');
// then
$select.trigger('change');
// or
$select.trigger('input');