Use a single ref object across multiple input elements
Asked Answered
A

2

6

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.

Armored answered 16/5, 2022 at 16:10 Comment(0)
M
10
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} />
Mobocracy answered 16/5, 2022 at 16:16 Comment(0)
M
1
import React, { useState,useRef } from "react";

const emailInputRef = useRef(null);
const passwordInputRef = useRef(null);

const saveData =(e) =>{
    console.log('emailInputRef.current.value',emailInputRef.current.value,'passwordInputRef.current.value',passwordInputRef.current.value)
}

return (
    <div>
        <form onSubmit={saveData}>
            <h2>Sign up here</h2>
            <label>Email Id</label>
            <input type="email" name="email" placeholder="Enter your mail id" id="email" ref={emailInputRef} />
            <label>Password</label>
            <input type="password" name="password" placeholder="Enter your password" id="password" ref={passwordInputRef}  />
<input type="submit" />
        </form>
            </div>)
Montcalm answered 2/9, 2022 at 15:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.