CRUD Operations in React: A Complete Guide
Introduction
CRUD (Create, Read, Update, Delete) operations are fundamental in web applications, enabling users to interact with data efficiently. React, a popular JavaScript library for building user interfaces, makes implementing CRUD operations seamless with state management and API handling.
In this comprehensive guide, we'll explore how to build a CRUD application in React using JSON Server as a mock backend. We’ll cover:
Setting up a React project
Installing dependencies
Creating a JSON Server
Implementing CRUD operations
Managing state with React hooks
By the end of this tutorial, you'll have a fully functional CRUD app where users can add, view, edit, and delete records.
Step 1: Create a React App
Use the following command to set up a new React project:
This creates a new React app and starts the development server.
Setting Up JSON Server
JSON Server is a lightweight backend to mock REST APIs.
Step 2: Install JSON Server
Run the following command to install JSON Server:
Next, create a db.json
file in the root of your project and add the following data:
Step 3: Start JSON Server
Run the following command to start the mock server:
This starts a REST API at http://localhost:5000/users
.
Implementing CRUD Operations
We'll build a user management system with the following features:
Create - Add a new user
Read - Display users
Update - Edit user details
Delete - Remove a user
Creating the Components
Step 4: Install Axios
We'll use Axios for making API requests:
Step 5: Create the Users.js
Component
Create a components
folder and add a Users.js
file. This component fetches and displays users.
Step 6: Create the UserForm.js
Component
This component handles user creation and editing.
Step 7: Create the App.js
Component
This component manages state and CRUD operations.
Running the Application
Now that we've set up the frontend and backend, start the application:
Start the JSON Server:
Start the React app:
Testing CRUD Functionality
Create a User
Enter a name and email
Click "Add User"
The user appears in the list
Read Users
Users are displayed on page load
Update a User
Click "Edit" next to a user
Update the name/email
Click "Update"
Delete a User
Click "Delete" next to a user
The user is removed from the list
Conclusion
In this guide, we built a simple React CRUD app using JSON Server. We covered:
Setting up a React project
Creating a mock backend with JSON Server
Implementing CRUD operations with Axios
Managing state with React hooks
This project provides a solid foundation for real-world applications, where you can replace JSON Server with a real database. Try extending this app by adding routing, validation, or authentication!