
what is crud operation in react js ?
In React.js, CRUD stands for Create, Read, Update, and Delete — the four basic operations for managing data in web applications. These operations usually involve interacting with a backend server using APIs (often RESTful APIs) and updating the UI accordingly.
CRUD Breakdown in React
Operation | Description | Example (UI Action) |
---|---|---|
Create | Add a new item | Filling a form to add a user |
Read | View/fetch data | Displaying a list of products |
Update | Edit existing data | Editing a product's details |
Delete | Remove an item | Clicking "Delete" on a user row |
CRUD operations in ReactJS refer to the four fundamental actions performed on data: Create, Read, Update, and Delete. These operations are crucial for building interactive applications that manage information.
1. Create (C):
This involves adding new data to your application's state or a backend database. In React, this typically involves using forms to collect user input and then updating the component's state (e.g., using useState hook) or sending a POST request to an API endpoint to store the data persistently.
2. Read (R):
This involves fetching and displaying existing data within your React components. Data can be read from the component's local state, a local storage mechanism (like localStorage), or by making GET requests to an API to retrieve data from a backend server. The retrieved data is then rendered in the UI, often in lists or tables.
3. Update (U):
This involves modifying existing data. In React, this often entails providing an interface (e.g., an editable form) for users to change data fields. Upon submission, the component's state is updated, or a PUT/PATCH request is sent to an API to update the data on the server.
4. Delete (D):
This involves removing data from your application. In React, this typically involves a user action (e.g., clicking a "delete" button) that triggers a function to remove the item from the component's state or send a DELETE request to an API endpoint.
Implementation in React:
State Management:
React's useState hook is commonly used to manage the local state of components, holding the data that is being manipulated by CRUD operations. For more complex applications, state management libraries like Redux or Zustand might be employed.
Forms:
HTML forms within React components are used to capture user input for creating and updating data.
API Integration:
For persistent storage, React applications often interact with backend APIs using libraries like Axios or the built-in fetch API to perform HTTP requests (POST, GET, PUT/PATCH, DELETE).
Conditional Rendering:
React's conditional rendering allows you to display different UI elements based on the state of the data (e.g., showing a loading indicator while fetching data, or an error message if an API request fails).
Example Use Case: React + JSONPlaceholder API
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const CrudExample = () => {
const [users, setUsers] = useState([]);
const [newUser, setNewUser] = useState('');
// READ
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/users')
.then(res => setUsers(res.data))
.catch(err => console.error(err));
}, []);
// CREATE
const addUser = () => {
axios.post('https://jsonplaceholder.typicode.com/users', { name: newUser })
.then(res => setUsers([...users, res.data]));
};
// UPDATE
const updateUser = (id) => {
axios.put(`https://jsonplaceholder.typicode.com/users/${id}`, { name: "Updated Name" })
.then(res => {
const updated = users.map(user => user.id === id ? res.data : user);
setUsers(updated);
});
};
// DELETE
const deleteUser = (id) => {
axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`)
.then(() => setUsers(users.filter(user => user.id !== id)));
};
return (
<div>
<h2>Users</h2>
<input value={newUser} onChange={(e) => setNewUser(e.target.value)} />
<button onClick={addUser}>Add User</button>
<ul>
{users.map(user => (
<li key={user.id}>
{user.name}
<button onClick={() => updateUser(user.id)}>Edit</button>
<button onClick={() => deleteUser(user.id)}>Delete</button>
</li>
))}
</ul>
</div>
);
};
export default CrudExample;
Summary
- React handles UI and state.
- Axios or fetch() handles communication with the backend.
- CRUD logic is implemented using event handlers and API calls.
- Backend (Node, PHP, Python, etc.) is usually responsible for storing the data.
Comments
Add new comment