Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 774
Chris Garcia Avatar asked Oct 13 '20 12:10

Chris Garcia


Video Answer


1 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

like image 174
Bruno Monteiro Avatar answered Sep 19 '22 14:09

Bruno Monteiro