- You can use
useRef
to get the values of input field in the form
useRef
is a buit-in hook to reference any DOM element
- Call useRef function and pass initial value. Common practice is to initialize to
null
- Returns ref object
- Create ref object and assign/associate to control
const nameRef = useRef(null);
<input ref={nameRef} />
console.log(nameRef.current.value)
current
prop returns referenced DOM element
if(nameRef.current !== null)
console.log(nameRef.current.value);
useRef<HTMLInputElement>();
- Initialize
useRef
with null. Current property of ref object reference DOM node. Initial value passed is used to set current property.
- Initially ref has no access to DOM node. DOM is created after react renders. After react renders component and creates DOM. Current prop is set to DOM and set to null when node is removed from screen
- Current prop points to either DOM or null
- If no value is passed then current prop will be undefined and it cause issues. Always initialize with null
const nameRef = useRef<HTMLInputElement>(null);
const ageRef = useRef<HTMLInputElement>(null);
const person = {
name: "",
age: 0,
};
const handleSubmit = (event: FormEvent) => {
event.preventDefault();
if (nameRef.current !== null) person.name = nameRef.current.value;
if (ageRef.current !== null) person.age = parseInt(ageRef.current.value);
};