When I change the value in an input, it can triggers onChange. When I click the button, it updates the value in state. Another component(an input) render again since state updated, it refresh on screen, but the onChange has not trigger.
There are some solutions but I found that they are not working on React 17.
I hope it will show
handleClick <input id="wav" value="new value">
handleChange triggered
In deed, it can only show.
handleClick <input id="wav" value="new value">
Some people suggest trigger onChange manually, but I don't know how to create a synthetic event. like calling handleChange(eventOnChange) in onClick(eventClick), but how can I create the real "eventOnChange", eg for formik.
Ref: React: trigger onChange if input value is changing by state?
class TestTriggerOnChange extends React.Component {
constructor(props) {
super(props)
this.state = {
value: 'original value'
}
}
handleChange (e) {
console.log('handleChange triggered')
}
handleClick () {
console.log('handleClick ', this.myinput)
this.setState({value: 'new value'})
var event = new Event('input', { bubbles: true });
this.myinput.dispatchEvent(event);
}
render () {
return (
<div>
<input id='wav' value={this.state.value} onChange={(e) => {this.handleChange(e)}} ref={(input)=> this.myinput = input}/>
<button onClick={this.handleClick.bind(this)}>Change Input</button>
</div>
)
}
}
package I used
"react": "^17.0.0",
"react-animation-components": "^3.0.0",
"react-dom": "^17.0.1",
"react-popper": "^2.2.4",
"react-redux": "^7.2.2",
"react-redux-form": "^1.16.14",
"react-router-dom": "^5.2.0",
"react-scripts": "^4.0.1",
"react-transition-group": "^4.4.1",
"reactstrap": "^8.8.1",
"redux": "3.7.2",
"redux-logger": "3.0.6",
"redux-thunk": "2.2.0",