December 17, 2023

Refs in React With Examples

In this tutorial you'll learn what are refs in React.

ref in React

ref, as it is quite easy to deduce, is a short for reference and that's what it is; a reference to the DOM nodes or React elements.

So refs provide one way to access DOM nodes or React elements. React emphasises more on using declarative way where we use state to change DOM, but with that way we just declare the function to change the state. When it will be called is not in our control.

With refs you can still access DOM nodes directly and as per React documentation there are a few good use cases for refs:

  1. Managing focus or text selection.
  2. Triggering imperative animations.
  3. Integrating with third-party DOM libraries.

Using ref in functional components

You can use built-in React hook useRef(initialValue) which returns a mutable ref object.

Some important points about refs-

  1. When you use useRef(initialValue) hook the returned ref object has a single property current which holds the reference value. This current property is initialized with the initialValue passed in the useRef hook. So, using ref.current gives a reference to the DOM element this ref is associated with.
  2. The returned object will persist for the full lifetime of the component, which means it won't change between component re-renderings.
  3. Mutating the .current property (assigning a new reference to .current) doesn’t cause a component re-rendering.

React refs example

In the example we'll have a form with two input elements for entering user name and city. We'll use refs-

  1. To focus on the name input field.
  2. To access values of the input elements so that we can do some basic validation like elements have some value or not.
ref in React
React refs with examples

Steps to access DOM elements using refs are as follows

  1. Define a ref using useRef() hook. const nameRef = useRef();
  2. Assign the reference to the ref attribute of the element <input type="text" id="name" ref={nameRef} />
  3. Once the association is done nameRef.current stores the reference to the input element.
import { useEffect, useRef, useState } from "react";
import { Alert, Card } from "react-bootstrap";

const UserDetails = () => {
  const nameRef = useRef();
  const cityRef = useRef();
  const [error, setError] = useState({show:false,
                                      title:'',
                                  errorMsg:''});
  useEffect(() => {
      nameRef.current.focus();
  }, []);
  const submitHandler = (event) => {
    event.preventDefault();
    const enteredName = nameRef.current.value;
    const enteredCity = cityRef.current.value;

    if(enteredName.trim() === '' || enteredCity.trim() === ''){
      setError({show:true,
          title:'Invalid Input',
          errorMsg:'Please enter a valid value for both name and city'});
      return;
    }
    console.log('Name ' + nameRef.current.value);
    console.log('City ' + cityRef.current.value);
    nameRef.current.value = '';
    cityRef.current.value = '';
  }
  const handleClose = () => {
    setError({show:false,
        title:'',
    errorMsg:''});
  }
  return (
    <Card className="mt-3 mx-auto" style={{ width: '25rem' }}>
      <form onSubmit={submitHandler}>
            <Alert show={error.show} variant="danger" onClose={handleClose} dismissible>
            <Alert.Heading>{error.title}</Alert.Heading>
            <p>{error.errorMsg}</p>
        </Alert>
        <label htmlFor="name">User Name</label>
        <input type="text" id="name" 
            placeholder="Enter user name" ref={nameRef} />
        <br/>
        <label htmlFor="city">City</label>
        <input type="text" id="city" 
            placeholder="Enter city" ref={cityRef} />
            <br/><br/>
        <div>
            <button onClick={submitHandler}>Submit</button>
        </div>
      </form>
    </Card>
  )
}
export default UserDetails;
  1. In the code, element focusing is done using the useEffect() hook. As we already know nameRef.current stores reference to the name input element when the component mounts. You can call focus() on the html element using this ref.
  2. nameRef.current and cityRef.current store references to the name and city input elements respectively. By accessing value attribute of these elements, we can get values of these inputs and do the required validation. This logic is written in submitHandler() function. Note that useState() hook is used to set the error state. An error object is used which has these properties show, title, errorMsg.
  3. Both name and city element values are reset using these statements.
    	nameRef.current.value = '';
    	cityRef.current.value = '';
    	

    This is not an ideal React way to modify the DOM element and any such action should be usually avoided.

That's all for the topic Refs in React With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment