Skip to main content

How to Make a CRUD App in React (Step by Step)

 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:

sh
npx create-react-app react-crud cd react-crud npm start

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:

sh
npm install -g json-server

Next, create a db.json file in the root of your project and add the following data:

json
{ "users": [ { "id": 1, "name": "John Doe", "email": "john@example.com" }, { "id": 2, "name": "Jane Doe", "email": "jane@example.com" } ] }

Step 3: Start JSON Server

Run the following command to start the mock server:

sh
json-server --watch db.json --port 5000

This starts a REST API at http://localhost:5000/users.


Implementing CRUD Operations

We'll build a user management system with the following features:

  1. Create - Add a new user

  2. Read - Display users

  3. Update - Edit user details

  4. Delete - Remove a user


Creating the Components

Step 4: Install Axios

We'll use Axios for making API requests:

sh
npm install axios

Step 5: Create the Users.js Component

Create a components folder and add a Users.js file. This component fetches and displays users.

jsx
import React, { useState, useEffect } from "react";
import axios from "axios"
const Users = ({ onEdit, onDelete }) => {
const [users, setUsers] = useState([]);
useEffect(() => { fetchUsers(); }, []);
const fetchUsers = async () => { 
const response = await axios.get("http://localhost:5000/users");
setUsers(response.data); }; 
return( <div> <h2>User List</h2> <ul>
 {users.map((user) => ( <li key={user.id}>
 {user.name} - {user.email} <button onClick={() =>
 onEdit(user)}>Edit</button>
<button onClick={() => onDelete(user.id)}>Delete</button> </li> ))} </ul> </div> );
 };
export default Users;

Step 6: Create the UserForm.js Component

This component handles user creation and editing.

jsx
import React, { useState, useEffect } from "react";
import axios from "axios";
const UserForm = ({ selectedUser, onUserAdded, onUserUpdated }) => {
const [name, setName] = useState("");
const [email, setEmail] = useState("");
useEffect(() =>
if (selectedUser) { setName(selectedUser.name);
setEmail(selectedUser.email); } }, [selectedUser]);
const handleSubmit = async (e) => { e.preventDefault(); 
const userData = { name, email }; if (selectedUser) {
await axios.put(`http://localhost:5000/users/${selectedUser.id}`, userData); onUserUpdated(); } 
else {
await axios.post("http://localhost:5000/users", userData); onUserAdded();
 } setName(""); setEmail("");
 }; 
return ( <form onSubmit={handleSubmit}> <h2>{selectedUser ? "Edit User" : "Add User"}</h2
<input type="text" placeholder="Name" value={name} onChange={(e) => setName(e.target.value)} required /> <input type="email" placeholder="Email"
value={email} onChange={(e) => setEmail(e.target.value)} required /> 
<button type="submit">{selectedUser ? "Update" : "Add"}</button
</form> );
 }; export default UserForm;

Step 7: Create the App.js Component

This component manages state and CRUD operations.

jsx
import React, { useState } from "react"
import Users from "./components/Users"
import UserForm from "./components/UserForm"
import axios from "axios";
const App = () => { 
const [selectedUser, setSelectedUser] = useState(null); 
const [reload, setReload] = useState(false); 
const handleUserAdded = () => setReload(!reload); 
const handleUserUpdated = () => { setReload(!reload); setSelectedUser(null);
 }; 
const handleEditUser = (user) => setSelectedUser(user); 
const handleDeleteUser = async (id) => { 
await axios.delete(`http://localhost:5000/users/${id}`);
setReload(!reload);
 }; 
return ( <div> <h1>React CRUD Application</h1
<UserForm selectedUser={selectedUser} onUserAdded={handleUserAdded} onUserUpdated={handleUserUpdated} />
<Users onEdit={handleEditUser} onDelete={handleDeleteUser} key={reload} /> </div> );
 };
export default App;

Running the Application

Now that we've set up the frontend and backend, start the application:

  1. Start the JSON Server:

    sh
    json-server --watch db.json --port 5000
  2. Start the React app:

    sh
    npm start

Testing CRUD Functionality

  1. Create a User

    • Enter a name and email

    • Click "Add User"

    • The user appears in the list

  2. Read Users

    • Users are displayed on page load

  3. Update a User

    • Click "Edit" next to a user

    • Update the name/email

    • Click "Update"

  4. 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!