CRUD operations in React —Create, Read, Update, and Delete—are the fundamental building blocks of any web application. In React, handling these operations is essential when working with data, whether it’s coming from a server or managed locally.
In this guide, we will walk you through building your very first CRUD application in React. You’ll learn how to:
- Set up your React application
- Perform Create, Read, Update, and Delete operations
- Manage state and handle user interactions
- Follow best practices for building React applications
This tutorial is suitable for beginners who are just starting with React, as well as experienced developers looking to reinforce their knowledge.
Table of Contents
Setting Up Your React Application
To start with React, you need to set up your project environment. If you don’t have React installed yet, you can use Create React App, which sets up everything you need in one go.
Step 1: Create a New React App
npx create-react-app crud-app
cd crud-app
npm start
This will set up your React app in a folder named crud-app
and start the development server.
Step 2: Creating the CRUD Components
Let’s break down the components we will create for our CRUD application:
- App.js: The main component to render the user interface.
- Form.js: A form to add and update data.
- List.js: A component to display the list of items.
- Item.js: A component to render each item in the list.
1. Creating the Form Component (Add & Update)
File: Form.js
In this component, users will be able to input new data or update existing data.
import React, { useState, useEffect } from 'react';
const Form = ({ currentItem, addItem, updateItem }) => {
const [title, setTitle] = useState('');
useEffect(() => {
if (currentItem) {
setTitle(currentItem.title);
}
}, [currentItem]);
const handleSubmit = (e) => {
e.preventDefault();
if (currentItem) {
updateItem({ ...currentItem, title });
} else {
addItem({ title });
}
setTitle('');
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
placeholder="Enter title"
required
/>
<button type="submit">{currentItem ? 'Update' : 'Add'} Item</button>
</form>
);
};
export default Form;
Explanation:
- useState: This hook stores the
title
of the item. - useEffect: It updates the
title
when thecurrentItem
changes (for updating an existing item). - handleSubmit: Handles form submission and either adds a new item or updates the existing one.
2. Creating the List Component (Display Items)
File: List.js
This component will display the list of items and handle the delete functionality.
import React from 'react';
import Item from './Item';
const List = ({ items, deleteItem, editItem }) => {
return (
<div>
<h2>Item List</h2>
<ul>
{items.map((item) => (
<Item key={item.id} item={item} deleteItem={deleteItem} editItem={editItem} />
))}
</ul>
</div>
);
};
export default List;
3. Creating the Item Component (Individual Item)
File: Item.js
This component will render each individual item with the ability to edit and delete.
import React from 'react';
const Item = ({ item, deleteItem, editItem }) => {
return (
<li>
{item.title}
<button onClick={() => editItem(item)}>Edit</button>
<button onClick={() => deleteItem(item.id)}>Delete</button>
</li>
);
};
export default Item;
4. Putting It All Together (App Component)
File: App.js
Now, let’s combine everything in the App.js
file.
import React, { useState } from 'react';
import Form from './Form';
import List from './List';
const App = () => {
const [items, setItems] = useState([]);
const [currentItem, setCurrentItem] = useState(null);
const addItem = (item) => {
setItems([...items, { ...item, id: Date.now() }]);
};
const updateItem = (updatedItem) => {
const updatedItems = items.map((item) =>
item.id === updatedItem.id ? updatedItem : item
);
setItems(updatedItems);
setCurrentItem(null); // Clear current item after update
};
const deleteItem = (id) => {
setItems(items.filter((item) => item.id !== id));
};
const editItem = (item) => {
setCurrentItem(item);
};
return (
<div>
<h1>CRUD Application</h1>
<Form currentItem={currentItem} addItem={addItem} updateItem={updateItem} />
<List items={items} deleteItem={deleteItem} editItem={editItem} />
</div>
);
};
export default App;
Output:
Explanation:
- useState: Manages the list of items and the currently selected item for editing.
- add Item: Adds a new item to the list.
- update Item: Updates an existing item in the list.
- delete Item: Deletes an item from the list.
- edit Item: Sets the item for editing when the “Edit” button is clicked.
Best Practices for Building a CRUD Application in React
- State Management: Use hooks like
useState
to manage local component state, anduseEffect
for side effects like fetching data or updating the DOM. - Component Modularity: Break down your application into reusable components like
Form
,List
, andItem
for better maintainability. - Error Handling: Always handle possible errors, especially for operations like fetching data or interacting with APIs.
- Optimizing Performance: Consider using
React.memo
for memoizing components anduseCallback
for optimizing functions that are passed as props. - User Experience: Add loading indicators when data is being fetched or processed, and provide feedback on successful or failed actions (e.g., item added, updated, or deleted).
FAQs
Q1. What are CRUD operations?
CRUD stands for Create, Read, Update, and Delete—the four basic operations for managing data in any web application.
Q2. How does React manage state for CRUD operations?
React uses the useState
hook to manage local state. For CRUD operations, you can store the data in the state and update it based on user actions (like adding, updating, or deleting an item).
Q3. Can I use external APIs in this CRUD application?
Yes, you can integrate APIs to fetch or send data using methods like Axios or Fetch. Instead of managing data locally, you can make API calls to handle CRUD operations.
Q4. How do I handle validation in the form?
You can use the required
attribute in form elements for basic validation or integrate libraries like Formik or React Hook Form for more advanced validation.
Q5. Can I add features like pagination or search to this CRUD app?
Yes, pagination and search are common features in CRUD applications. You can implement pagination by splitting the list into pages, and implement search by filtering the displayed list based on the search term.
Thank you for reading! If you found this guide helpful and want to stay updated on more React.js content, be sure to follow us for the latest tutorials and insights: JavaDZone React.js Tutorials. Happy coding!