How to Do CRUD Operations in ReactJS: A Step-by-Step Guide

How to Do CRUD Operations in ReactJS

CRUD operations—Create, Read, Update, and Delete—are essential for managing data in web applications. This guide will show you how to implement these operations in ReactJS, providing a structured approach with clear file and folder naming.

Project Structure

We’ll set up a basic React application with the following structure:
my-app/
├── public/
├── src/
│   ├── components/
│   │   ├── CreateItem.js
│   │   ├── ReadItems.js
│   │   ├── UpdateItem.js
│   │   ├── DeleteItem.js
│   ├── App.js
│   ├── index.js
└── package.json

1. Setting Up Your ReactJS Environment

First, create a new React app using Create React App:

npx create-react-app my-app
cd my-app
npm start

2. Create Item (Create Operation)

To add new data, we’ll create a form component. Create a file named CreateItem.js in the src/components folder:

// src/components/CreateItem.js

import React, { useState } from 'react';

const CreateItem = ({ onCreate }) => {
  const [item, setItem] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    onCreate(item);
    setItem('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text" 
        value={item} 
        onChange={(e) => setItem(e.target.value)} 
        placeholder="Enter item"
      />
      <button type="submit">Add Item</button>
    </form>
  );
};

export default CreateItem;

3. Read Items (Read Operation)

To fetch and display data, create a file named ReadItems.js in the src/components folder:

// src/components/ReadItems.js

import React, { useEffect, useState } from 'react';

const ReadItems = () => {
  const [items, setItems] = useState([]);

  useEffect(() => {
    fetch('https://api.example.com/items')
      .then(response => response.json())
      .then(data => setItems(data));
  }, []);

  return (
    <ul>
      {items.map(item => (
        <li key={item.id}>{item.name}</li>
      ))}
    </ul>
  );
};

export default ReadItems;

4. Update Item (Update Operation)

To update existing data, create a file named UpdateItem.js in the src/components folder:

// src/components/UpdateItem.js

import React, { useState } from 'react';

const UpdateItem = ({ item, onUpdate }) => {
  const [newItem, setNewItem] = useState(item.name);

  const handleSubmit = (e) => {
    e.preventDefault();
    onUpdate(item.id, newItem);
  };

  return (
    <form onSubmit={handleSubmit}>
      <input 
        type="text" 
        value={newItem} 
        onChange={(e) => setNewItem(e.target.value)} 
      />
      <button type="submit">Update Item</button>
    </form>
  );
};

export default UpdateItem;

5. Delete Item (Delete Operation)

To delete data, create a file named DeleteItem.js in the src/components folder:

// src/components/DeleteItem.js

import React from 'react';

const DeleteItem = ({ itemId, onDelete }) => {
  return (
    <button onClick={() => onDelete(itemId)}>Delete</button>
  );
};

export default DeleteItem;

6. Integrating Components in App

In the src folder, open App.js and import the created components. Use them as follows:

// src/App.js

import React, { useState } from 'react';
import CreateItem from './components/CreateItem';
import ReadItems from './components/ReadItems';
import UpdateItem from './components/UpdateItem';
import DeleteItem from './components/DeleteItem';

const App = () => {
  const [items, setItems] = useState([]);
  const [itemToUpdate, setItemToUpdate] = useState(null);

  const handleCreate = (newItem) => {
    // Implement logic to create an item
    // Example: setItems([...items, { id: items.length, name: newItem }]);
  };

  const handleUpdate = (id, updatedItem) => {
    // Implement logic to update an item
  };

  const handleDelete = (id) => {
    // Implement logic to delete an item
  };

  return (
    <div>
      <h1>CRUD Operations in ReactJS</h1>
      <CreateItem onCreate={handleCreate} />
      <ReadItems items={items} />
      {itemToUpdate && (
        <UpdateItem item={itemToUpdate} onUpdate={handleUpdate} />
      )}
      <DeleteItem onDelete={handleDelete} />
    </div>
  );
};

export default App;

Conclusion

This structured approach provides a foundation for implementing CRUD operations in ReactJS. You can expand and modify these components based on your application’s requirements. For more in-depth tutorials and resources, consider checking out the following links:

 

Writing by Kanha Jatthap

Published on Development Query

This tutorial covers the basics of CRUD operations in ReactJS. You can integrate these components into your application to manage data effectively and build robust, dynamic applications.

Read more… 

Share the Post:

Table of Contents

Leave a Reply

Your email address will not be published. Required fields are marked *

Join Our Newsletter