DEV Community

Serge Jabo Byusa
Serge Jabo Byusa

Posted on

Working with Ref in React

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';
Enter fullscreen mode Exit fullscreen mode

Step 2

inside the method, set the values of refs

const enteredUsername1 = nameInputRef.current.value;
const enteredUserAge1 = ageInputRef.current.value; 
Enter fullscreen mode Exit fullscreen mode

Step 3
use the ref

 ref={nameInputRef}
Enter fullscreen mode Exit fullscreen mode

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;

Enter fullscreen mode Exit fullscreen mode

NB: Using Ref makes the inputs to be uncontrolled components (value in them is not controlled by react)

Top comments (0)