When you need to only read a value but no need to change it just use Refs (better than State in this case) But in general rarely use Refs, just use useState
Step 1
import useRef from react
import React, {useRef } from 'react';
Step 2
inside the method, set the values of refs
const enteredUsername1 = nameInputRef.current.value;
const enteredUserAge1 = ageInputRef.current.value;
Step 3
use the ref
ref={nameInputRef}
Example of full code
import React, {useRef } from 'react';
import Card from '../UI/Card';
import classes from './AddUser.module.css';
const AddUser = (props) => {
const nameInputRef = useRef();
const ageInputRef = useRef();
const addUserHandler = (event) => {
event.preventDefault();
const enteredUsername1 = nameInputRef.current.value;
const enteredUserAge1 = ageInputRef.current.value;
props.onAddUser(enteredUsername1, enteredUserAge1);
//in case you want to set your ref to null
nameInputRef.current.value = ''
ageInputRef.current.value = ''
};
return (
<div>
<Card className={classes.input}>
<form onSubmit={addUserHandler}>
<label htmlFor="username">Username</label>
<input
id="username"
type="text"
ref={nameInputRef}
/>
<label htmlFor="age">Age (Years)</label>
<input
id="age"
type="number"
ref={ageInputRef}
/>
<button type="submit">Add User</button>
</form>
</Card>
</div>
);
};
export default AddUser;
NB: Using Ref makes the inputs to be uncontrolled components (value in them is not controlled by react)
Top comments (0)