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
- Setting Up a New React Project
- Syntax of
useRef - Real-Time Project: Focus Management in a Form
- Project Setup
- Creating the Form Component
- Using
useRefto Access DOM Elements - Managing Focus with
useRef
- Conclusion
Setting Up a New React Project
First, let’s create a new React project using the create-react-app tool.
-
Open your terminal and run the following command:
npx create-react-app useref-focus-app -
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
useRefhook creates a ref object (inputRef). - The
focusInputfunction sets focus to the input element usinginputRef.current.focus(). - The
refattribute is used to attach the ref to the input element.
Real-Time Project: Focus Management in a Form
Project Setup
-
Open the project directory in your code editor.
-
Remove the default content from
src/App.jsandsrc/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
-
Create a new file named
Form.jsin thesrcdirectory. -
Define the
Formcomponent:// 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; -
Create a CSS file named
Form.cssto 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
-
Create Refs: The
useRefhook 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); -
Attach Refs to Input Fields: The
refattribute 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
-
Focus Management: The
focusFirstNamefunction sets focus to the first name input field usingfirstNameRef.current.focus().const focusFirstName = () => { firstNameRef.current.focus(); }; -
Handle Form Submission: The
handleSubmitfunction 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}`); }; -
Focus Button: The button with the
onClickevent handler calls thefocusFirstNamefunction 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.