Sometimes, we want to trigger onChange if input value is changing by state with React.
In this article, we’ll look at how to trigger onChange if input value is changing by state with React.
How to trigger onChange if input value is changing by state with React?
To trigger onChange if input value is changing by state with React, we can watch for state change with the useEffect hook.
For instance, we write
const MyInputComponent = () => {
const [numberValue, setNumberValue] = useState(0);
const numberInput = useRef(null);
useEffect(() => {
numberInput.current.dispatchEvent(
new Event("change", {
detail: {
newValue: numberValue,
},
bubbles: true,
cancelable: true,
})
);
}, [numberValue]);
return (
<>
<input
type="number"
value={numberValue}
ref={numberInput}
inputMode="numeric"
onChange={(e) => setNumberValue(e.target.value)}
/>
</>
);
};
to add an input that’s bound to the numberValue state with the onChange and value props.
value is set to numberValue to display numberValue as the input value.
onChange is set to (e) => setNumberValue(e.target.value) to set the numberValue state to a value.
Then we call useEffect hook with [numberValue] to call the useEffect callback when the numberValue state changes.
Conclusion
To trigger onChange if input value is changing by state with React, we can watch for state change with the useEffect hook.