How to Build a Simple CRUD Application with React
Creating a simple CRUD (Create, Read, Update, Delete) application is one of the best ways to understand the foundational concepts of React. Whether you're a beginner or looking to polish your skills, building a CRUD app will give you hands-on experience with core React principles, state management, and component lifecycle. In this article, we will walk through the process of building a simple CRUD application using React, complete with code examples, tips, and best practices.
What is CRUD?
CRUD stands for Create, Read, Update, and Delete. These are the four basic operations that can be performed on data in a database. Most applications require these functionalities to manage data effectively. A CRUD application will allow users to:
- Create new entries
- Read or view existing entries
- Update existing entries
- Delete entries
Use Cases for CRUD Applications
CRUD applications are widely used across various domains, including:
- Task Management: Apps that allow users to create, manage, and delete tasks.
- Note-taking Applications: Apps that enable users to write, read, edit, and delete notes.
- E-commerce Platforms: Inventory management systems for adding, viewing, modifying, and removing products.
Setting Up Your React Environment
Before we dive into coding, let's set up our React environment. We will use Create React App, a tool that sets up a modern web app by running one command.
Step 1: Create a New React App
Open your terminal and run the following command:
npx create-react-app my-crud-app
cd my-crud-app
Step 2: Install Dependencies
For our CRUD operations, we'll use uuid
to generate unique IDs for our entries. Install it with:
npm install uuid
Building the CRUD Application
Now that we have our environment set up, let’s create a simple task manager as our CRUD application.
Step 3: Structuring the Project
Inside the src
folder, create a new folder named components
. We will create the following components:
App.js
: The main component.TaskForm.js
: The form for adding and editing tasks.TaskList.js
: The list to display tasks.
Step 4: Creating the App Component
Start by modifying App.js
to include the main structure and state management.
// src/App.js
import React, { useState } from 'react';
import TaskForm from './components/TaskForm';
import TaskList from './components/TaskList';
import { v4 as uuidv4 } from 'uuid';
const App = () => {
const [tasks, setTasks] = useState([]);
const [currentTask, setCurrentTask] = useState(null);
const addTask = (task) => {
setTasks([...tasks, { id: uuidv4(), ...task }]);
};
const updateTask = (task) => {
setTasks(tasks.map(t => (t.id === task.id ? task : t)));
};
const deleteTask = (id) => {
setTasks(tasks.filter(task => task.id !== id));
};
return (
<div>
<h1>Simple CRUD Application</h1>
<TaskForm addTask={addTask} updateTask={updateTask} currentTask={currentTask} />
<TaskList tasks={tasks} deleteTask={deleteTask} setCurrentTask={setCurrentTask} />
</div>
);
};
export default App;
Step 5: Creating the TaskForm Component
Now, create the TaskForm
component to handle adding and updating tasks.
// src/components/TaskForm.js
import React, { useState, useEffect } from 'react';
const TaskForm = ({ addTask, updateTask, currentTask }) => {
const [task, setTask] = useState({ title: '', description: '' });
useEffect(() => {
if (currentTask) {
setTask(currentTask);
} else {
setTask({ title: '', description: '' });
}
}, [currentTask]);
const handleSubmit = (e) => {
e.preventDefault();
if (currentTask) {
updateTask(task);
} else {
addTask(task);
}
setTask({ title: '', description: '' });
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
placeholder="Task Title"
value={task.title}
onChange={(e) => setTask({ ...task, title: e.target.value })}
required
/>
<textarea
placeholder="Task Description"
value={task.description}
onChange={(e) => setTask({ ...task, description: e.target.value })}
required
></textarea>
<button type="submit">{currentTask ? 'Update Task' : 'Add Task'}</button>
</form>
);
};
export default TaskForm;
Step 6: Creating the TaskList Component
Next, create the TaskList
component to display the tasks and handle deletions.
// src/components/TaskList.js
import React from 'react';
const TaskList = ({ tasks, deleteTask, setCurrentTask }) => {
return (
<ul>
{tasks.map((task) => (
<li key={task.id}>
<h3>{task.title}</h3>
<p>{task.description}</p>
<button onClick={() => setCurrentTask(task)}>Edit</button>
<button onClick={() => deleteTask(task.id)}>Delete</button>
</li>
))}
</ul>
);
};
export default TaskList;
Step 7: Running Your Application
Now that we have all components set up, run your application with:
npm start
Navigate to http://localhost:3000/
in your browser to see your CRUD application in action. You can add tasks, edit them, and delete them as needed.
Troubleshooting Common Issues
- State Not Updating: Ensure you're using the correct state management methods.
setState
should be called with the previous state. - Component Not Rendering: Check that your component imports and exports are correctly set up.
Conclusion
Congratulations! You've built a simple CRUD application using React. This project has provided you with a solid understanding of how to manage state, create components, and handle user interactions. As you continue your journey in React development, consider expanding your application by adding features such as user authentication, a backend API, or enhanced styling.
By mastering CRUD operations, you're well on your way to creating more complex applications. Happy coding!