While it's easy to update an input's value using a ref, that doesn't trigger the input's onChange event, which may be an issue if you're relying on onChange to fire when the input value changes.
If you don't need the onChange event to fire, this might be good enough:

if (props.inputRef) { // props.inputRef is a reference to the input
    props.inputRef.current.value = "new value";
}

But if you do need the onChange event to fire, this workaround sets the value and triggers the event:

const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, 'value')?.set;
nativeInputValueSetter?.call(props.inputRef?.current, value); // props.inputRef is a reference to the input
const event = new Event('change', { bubbles: true });
props.inputRef?.current?.dispatchEvent(event);

Source: https://stackoverflow.com/a/46012210/4669143

Published On: March 12, 2024Categories: ReactTags: , , ,