I captured an element with the useRef hook of React. if I use console.log(this.inputRef) I get:
<input aria-invalid="false" autocomplete="off" class="MuiInputBase-input-409 MuiInput-input-394" placeholder="Type ItemCode or scan barcode" type="text" value="2">
Is there a way to change the value of that element using this.inputRef? and then force its re-render?
It sounds like what you are looking for is the ImperativeHandle hook.
From React docs:
useImperativeHandle customizes the instance value that is exposed to parent components when using ref
The below code should work for you:
function ValueInput(props, ref) {
const inputRef = useRef();
useImperativeHandle(ref, () => ({
changeValue: (newValue) => {
inputRef.current.value = newValue;
}
}));
return <input ref={inputRef} aria-invalid="false" autocomplete="off" class="MuiInputBase-input-409 MuiInput-input-394" placeholder="Type ItemCode or scan barcode" type="text" value="2">
}
ValueInput = forwardRef(ValueInput);
Documentation: https://reactjs.org/docs/hooks-reference.html#useimperativehandle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With