Search code examples
reactjsformsinputrefuse-ref

Use a single ref object across multiple input elements


I have a form that contains a number of input elements. I want to access the values of these inputs in the parent component. For this, I could use state but I am exploring the use of refs at the moment. I understand that it is possible to record the value of an input as such (so that the inputRef object updates as the value of the input changes)

const inputRef = useRef()

return(
  <input id = "example" ref = {inputRef} />
);

I am wondering if it is possible to use the same ref object across multiple inputs, such that inputRef.current is an object that uses the input IDs as keys.

For instance:

inputRef = useRef()

return(
  <>
    <input id = "fname" ref = {"set inputRef.current.fname"} />
    <input id = "lname" ref = {"set inputRef.current.lname"} />
    <input id = "email" ref = {"set inputRef.current.email"} />
  </>
);

Such an approach would save the verbose creation of multiple ref objects.


Solution

  • inputRef = useRef()
    
    <input id = "fname" ref = {ref => inputRef.current.fname = ref} />
    <input id = "lname" ref = {ref => inputRef.current.lname = ref} />
    <input id = "email" ref = {ref => inputRef.current.email = ref} />