React useRef Hook

Introduction

In this chapter, we will explore the useRef hook in React. This hook allows you to create a mutable object that persists across renders. useRef is primarily used to access DOM elements directly and store mutable values that do not cause re-renders when updated. We will create a new React project from scratch, explain the syntax of useRef, and walk through a real-time project step by step to demonstrate its usage.

Table of Contents

  1. Setting Up a New React Project
  2. Syntax of useRef
  3. Real-Time Project: Focus Management in a Form
    • Project Setup
    • Creating the Form Component
    • Using useRef to Access DOM Elements
    • Managing Focus with useRef
  4. Conclusion

Setting Up a New React Project

First, let’s create a new React project using the create-react-app tool.

  1. Open your terminal and run the following command:

    npx create-react-app useref-focus-app
    
  2. Navigate to the project directory:

    cd useref-focus-app
    

Syntax of useRef

The useRef hook returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The ref object persists for the lifetime of the component.

Syntax

const refContainer = useRef(initialValue);
  • initialValue: The initial value of the ref object.

Example

import React, { useRef } from 'react';

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

  const focusInput = () => {
    inputRef.current.focus();
  };

  return (
    <div>
      <input ref={inputRef} type="text" />
      <button onClick={focusInput}>Focus Input</button>
    </div>
  );
}

export default MyComponent;

Explanation:

  • The useRef hook creates a ref object (inputRef).
  • The focusInput function sets focus to the input element using inputRef.current.focus().
  • The ref attribute is used to attach the ref to the input element.

Real-Time Project: Focus Management in a Form

Project Setup

  1. Open the project directory in your code editor.

  2. Remove the default content from src/App.js and src/App.css:

    // src/App.js
    import React from 'react';
    import './App.css';
    import Form from './Form';
    
    function App() {
      return (
        <div className="App">
          <h1>Focus Management with useRef</h1>
          <Form />
        </div>
      );
    }
    
    export default App;
    
    /* src/App.css */
    .App {
      text-align: center;
      padding: 20px;
    }
    
    h1 {
      margin-bottom: 20px;
    }
    

Creating the Form Component

  1. Create a new file named Form.js in the src directory.

  2. Define the Form component:

    // src/Form.js
    import React, { useRef } from 'react';
    import './Form.css';
    
    function Form() {
      const firstNameRef = useRef(null);
      const lastNameRef = useRef(null);
      const emailRef = useRef(null);
    
      const handleSubmit = (event) => {
        event.preventDefault();
        alert(`First Name: ${firstNameRef.current.value}\nLast Name: ${lastNameRef.current.value}\nEmail: ${emailRef.current.value}`);
      };
    
      const focusFirstName = () => {
        firstNameRef.current.focus();
      };
    
      return (
        <div className="container">
          <form onSubmit={handleSubmit}>
            <div className="form-group">
              <label htmlFor="firstName">First Name</label>
              <input ref={firstNameRef} type="text" id="firstName" className="form-control" />
            </div>
            <div className="form-group">
              <label htmlFor="lastName">Last Name</label>
              <input ref={lastNameRef} type="text" id="lastName" className="form-control" />
            </div>
            <div className="form-group">
              <label htmlFor="email">Email</label>
              <input ref={emailRef} type="email" id="email" className="form-control" />
            </div>
            <button type="submit" className="btn btn-primary">Submit</button>
            <button type="button" className="btn btn-secondary" onClick={focusFirstName}>Focus First Name</button>
          </form>
        </div>
      );
    }
    
    export default Form;
    
  3. Create a CSS file named Form.css to style the Form component:

    /* src/Form.css */
    .container {
      max-width: 600px;
      margin: 0 auto;
      text-align: left;
    }
    
    .form-group {
      margin-bottom: 15px;
    }
    
    .form-control {
      width: 100%;
      padding: 10px;
      margin: 5px 0;
      box-sizing: border-box;
      border: 1px solid #ccc;
      border-radius: 4px;
    }
    
    .btn {
      padding: 10px 15px;
      margin-right: 10px;
      border: none;
      border-radius: 4px;
      cursor: pointer;
    }
    
    .btn-primary {
      background-color: #007bff;
      color: white;
    }
    
    .btn-primary:hover {
      background-color: #0056b3;
    }
    
    .btn-secondary {
      background-color: #6c757d;
      color: white;
    }
    
    .btn-secondary:hover {
      background-color: #5a6268;
    }
    

Using useRef to Access DOM Elements

  1. Create Refs: The useRef hook is used to create refs for the first name, last name, and email input fields.

    const firstNameRef = useRef(null);
    const lastNameRef = useRef(null);
    const emailRef = useRef(null);
    
  2. Attach Refs to Input Fields: The ref attribute is used to attach the refs to the respective input fields.

    <input ref={firstNameRef} type="text" id="firstName" className="form-control" />
    <input ref={lastNameRef} type="text" id="lastName" className="form-control" />
    <input ref={emailRef} type="email" id="email" className="form-control" />
    

Managing Focus with useRef

  1. Focus Management: The focusFirstName function sets focus to the first name input field using firstNameRef.current.focus().

    const focusFirstName = () => {
      firstNameRef.current.focus();
    };
    
  2. Handle Form Submission: The handleSubmit function displays the values of the input fields in an alert message.

    const handleSubmit = (event) => {
      event.preventDefault();
      alert(`First Name: ${firstNameRef.current.value}\nLast Name: ${lastNameRef.current.value}\nEmail: ${emailRef.current.value}`);
    };
    
  3. Focus Button: The button with the onClick event handler calls the focusFirstName function to set focus to the first name input field.

    <button type="button" className="btn btn-secondary" onClick={focusFirstName}>Focus First Name</button>
    

Conclusion

In this chapter, we created a new React project and explored the useRef hook. We learned the syntax of useRef and walked through a real-time project step by step to create a form with focus management. By understanding and using the useRef hook, you can access and interact with DOM elements directly in your functional components, making your React applications more dynamic and interactive.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top