Change input value with useRef

Viewed 45888

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?

3 Answers

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

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

may be this can help

return(
    <input type="text" ref={inptRef}  />
    <button onClick={()=>inptRef.current.value = ""}>clear input</button>

)
Related