Introduction
In this chapter, we will explore the useId
hook in React. This hook generates unique IDs that can be used for accessibility purposes, such as associating form inputs with their labels. It ensures that the IDs are unique across the entire application, even when components are rendered multiple times. We will create a new React project from scratch, explain the syntax of useId
, 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
useId
- Real-Time Project: Employee Management System with Accessible Forms
- Project Setup
- Creating the EmployeeForm Component
- Using
useId
to Generate Unique IDs
- 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 useid-employee-app
-
Navigate to the project directory:
cd useid-employee-app
Syntax of useId
The useId
hook generates a unique ID that is stable across server and client renders. This can be useful for associating form inputs with their labels, improving accessibility.
Syntax
const id = useId();
id
: The unique ID generated by theuseId
hook.
Example
import React, { useId } from 'react'; function MyComponent() { const id = useId(); return ( <div> <label htmlFor={id}>Name</label> <input id={id} type="text" /> </div> ); } export default MyComponent;
Explanation:
- The
useId
hook generates a unique ID. - This ID is used for the
id
attribute of the input and thehtmlFor
attribute of the label to associate them.
Real-Time Project: Employee Management System with Accessible Forms
Project Setup
-
Open the project directory in your code editor.
-
Remove the default content from
src/App.js
andsrc/App.css
:// src/App.js import React from 'react'; import './App.css'; import EmployeeForm from './EmployeeForm'; function App() { return ( <div className="App"> <h1>Employee Management System</h1> <EmployeeForm /> </div> ); } export default App;
/* src/App.css */ .App { text-align: center; padding: 20px; } h1 { margin-bottom: 20px; }
Creating the EmployeeForm Component
-
Create a new file named
EmployeeForm.js
in thesrc
directory. -
Define the
EmployeeForm
component:// src/EmployeeForm.js import React, { useState, useId } from 'react'; import './EmployeeForm.css'; function EmployeeForm() { const id = useId(); const firstNameId = `${id}-firstName`; const lastNameId = `${id}-lastName`; const emailId = `${id}-email`; const [employee, setEmployee] = useState({ firstName: '', lastName: '', email: '' }); const handleChange = (e) => { const { name, value } = e.target; setEmployee((prevEmployee) => ({ ...prevEmployee, [name]: value })); }; const handleSubmit = (e) => { e.preventDefault(); console.log('Employee data submitted:', employee); }; return ( <div className="container mt-5"> <form onSubmit={handleSubmit}> <div className="form-group"> <label htmlFor={firstNameId}>First Name</label> <input type="text" id={firstNameId} name="firstName" className="form-control" value={employee.firstName} onChange={handleChange} /> </div> <div className="form-group"> <label htmlFor={lastNameId}>Last Name</label> <input type="text" id={lastNameId} name="lastName" className="form-control" value={employee.lastName} onChange={handleChange} /> </div> <div className="form-group"> <label htmlFor={emailId}>Email</label> <input type="email" id={emailId} name="email" className="form-control" value={employee.email} onChange={handleChange} /> </div> <button type="submit" className="btn btn-primary">Submit</button> </form> </div> ); } export default EmployeeForm;
Using useId
to Generate Unique IDs
-
Generate Unique IDs: The
useId
hook is used to generate a base ID, and specific IDs for each form input are derived from this base ID.const id = useId(); const firstNameId = `${id}-firstName`; const lastNameId = `${id}-lastName`; const emailId = `${id}-email`;
-
Associate Labels and Inputs: The generated IDs are used for the
id
attributes of the inputs and thehtmlFor
attributes of the labels.<label htmlFor={firstNameId}>First Name</label> <input type="text" id={firstNameId} name="firstName" className="form-control" value={employee.firstName} onChange={handleChange} /> <label htmlFor={lastNameId}>Last Name</label> <input type="text" id={lastNameId} name="lastName" className="form-control" value={employee.lastName} onChange={handleChange} /> <label htmlFor={emailId}>Email</label> <input type="email" id={emailId} name="email" className="form-control" value={employee.email} onChange={handleChange} />
Creating a CSS File for EmployeeForm
-
Create a CSS file named
EmployeeForm.css
to style theEmployeeForm
component:/* src/EmployeeForm.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; }
Conclusion
In this chapter, we created a new React project and explored the useId
hook. We learned the syntax of useId
and walked through a real-time project step by step to create an Employee Management System application with accessible forms. By understanding and using the useId
hook, you can generate unique IDs that ensure your form elements are properly associated, improving the accessibility of your React applications.