Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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} />
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading