Reputation: 9555
If I set the input with a ref
refName.current.value = 'my value'
then the value will be set in the DOM but the onChange event does not fire.
How do I get the onchange to fire when using a ref
import React, { useRef } from 'react';
const AddTodoArea = observer((props: any) => {
const [name, setName] = useState('')
const refName = useRef(null);
return (
<div>
<input
type="text"
placeholder="Name"
ref={refName}
value={name}
onChange={(e: React.ChangeEvent<HTMLInputElement>): void => {
console.log('my value is set by a ref')
}}
/>
);
});
export default AddTodoArea;
Upvotes: 0
Views: 516
Reputation: 5854
Please check this example for your requirement. Hope it helps you.
import React from "react";
export default class NameForm extends React.Component {
constructor(props) {
super(props);
this.state = {value: ''};
this.inputRef = React.createRef();
}
onChange = (event) =>{
this.setState({value: event.target.value});
alert('onChange is fired');
};
clickHandler = (event) =>{
event.preventDefault();
// let input = document.querySelector('#message');
// let nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
// nativeInputValueSetter.call(input, 'This is value of text input');
// let customEvent = new Event('input', {bubbles: true});
// input.dispatchEvent(customEvent);
// This is based on your requirement
let nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
nativeInputValueSetter.call(this.inputRef.current, 'Hi there');
let customEvent = new Event('input', {bubbles: true});
this.inputRef.current.dispatchEvent(customEvent);
};
render() {
return (
<form>
<label>
Name:
<input ref={this.inputRef} id="message" type="text" value={this.state.value} onChange={this.onChange}/>
</label>
<input type="button" value="Click Me" onClick={this.clickHandler}/>
</form>
);
}
}
Upvotes: 2