'Change input value with useRef
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?
Solution 1:[1]
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
Solution 2:[2]
well, you could do:
<input ref={myRef} value={myRef.current.value} />
The only problem with that is that refs DO NOT update or reredender the component, so, the value would never update... rather than that it could throw you an error where you are attempting to make an uncontrolled input as controlled
Solution 3:[3]
I need to leave a comment here to say that Taha Jana Ismail's answer is downvoted, but setting theRef.current.value definitely works to update the value of the input.
If you set the ref above the return of your react function, put it in the ref attribute of the input element, and then modify the ref.current.value it for sure works.
Solution 4:[4]
may be this can help
return(
<input type="text" ref={inptRef} />
<button onClick={()=>inptRef.current.value = ""}>clear input</button>
)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | Chema |
Solution 3 | Bryan James Bassett |
Solution 4 | Taha Janan Ismail |