How to Use Refs in React: A Simple Guide with Code Examples

How to Use Refs in React: A Simple Guide with Code Examples

Refs and the DOM are important concepts in React that allow us to access and manipulate elements in the DOM directly. In this article, we'll explore how to use refs in React, and how they can be used to manipulate the DOM.

What are Refs?

Refs are a way to access and manipulate the DOM directly from a React component. They provide a way to get a reference to a particular DOM element so that you can access its properties and methods.

Using Refs in React

To use refs in React, we need to create a ref object and then attach it to the component that we want to reference. We can do this using the useRef hook, which returns a mutable ref object.

Let's look at an example of how to use refs in React. In this example, we'll create a simple form that allows users to input their name and then displays a greeting message when they submit the form.

import React, { useRef } from 'react';

function Greeting() {
  const nameRef = useRef(null);

  function handleSubmit(event) {
    event.preventDefault();
    alert(`Hello, ${nameRef.current.value}!`);
  }

  return (
    <form onSubmit={handleSubmit}>
      <label>
        Enter your name:
        <input type="text" ref={nameRef} />
      </label>
      <button type="submit">Submit</button>
    </form>
  );
}

export default Greeting;

In this example, we've created a ref object called nameRef using the useRef hook. We've then attached this ref to the input element using the ref attribute.

When the user submits the form, the handleSubmit function is called, which accesses the value of the input element using nameRef.current.value.

This allows us to display a personalized greeting message to the user.

Replicating the example

To replicate this example on your local machine, follow these steps:

  1. Create a new React app using the create-react-app tool by running the following command in your terminal:
npx create-react-app refs-demo
  1. Navigate to the refs-demo directory and open the src/App.js file.

  2. Replace the contents of App.js with the example code above.

  3. Save the file and start the development server by running the following command:

npm start
  1. Open your browser and navigate to http://localhost:3000. You should see a form that allows you to enter your name.

  2. Enter your name and click the Submit button to see the personalized greeting message.

Conclusion

Refs are a powerful tool that allow us to access and manipulate the DOM directly from a React component. They can be used to access form inputs, video players, and other HTML elements, and provide a way to interact with the user in real-time. By using the useRef hook, we can easily create refs in our React components and take advantage of this powerful feature.