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.
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} />
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>)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With