What are refs in React?

Experience Level: Junior
Tags: React

Answer

Refs in React are a way to access and manipulate the DOM elements directly. They provide a way to get a reference to a specific element in the component and then use it to perform actions like setting focus, changing styles, or triggering animations. Refs are created using the ref attribute in JSX and can be assigned to a variable in the component using the useRef hook. For example, let's say we have a form component with an input field that we want to focus on when the component mounts. We can create a ref using the useRef hook and then assign it to the input field using the ref attribute. Then, in the useEffect hook, we can call the focus method on the ref to set the focus on the input field.


import React, { useRef, useEffect } from 'react';

function Form() {
  const inputRef = useRef(null);

  useEffect(() => {
    inputRef.current.focus();
  }, []);

  return (
    <form>
      <label htmlFor="name">Name:</label>
      <input type="text" id="name" ref={inputRef} />
    </form>
  );
}
In this example, we create a ref using the useRef hook and assign it to the input field using the ref attribute. Then, in the useEffect hook, we call the focus method on the ref to set the focus on the input field when the component mounts. Refs can also be used to access child components and their methods. For example, let's say we have a parent component with a child component that has a method we want to call from the parent. We can create a ref in the parent component using the useRef hook and then assign it to the child component using the ref attribute. Then, we can call the child component's method using the ref.

import React, { useRef } from 'react';
import Child from './Child';

function Parent() {
  const childRef = useRef(null);

  const handleClick = () => {
    childRef.current.doSomething();
  };

  return (
    <div>
      <button onClick={handleClick}>Do something</button>
      <Child ref={childRef} />
    </div>
  );
}
In this example, we create a ref using the useRef hook in the parent component and assign it to the child component using the ref attribute. Then, we create a handleClick function that calls the child component's doSomething method using the ref. This allows us to access and manipulate the child component's methods from the parent component.

React for beginners
React for beginners

Are you learning React ? Try our test we designed to help you progress faster.

Test yourself