DEV Community

Ranjith srt
Ranjith srt

Posted on

React - Crud Application

A **CRUD application** is a software program that performs four main operations:

- **C**reate: Add new data (e.g., creating a new user or post).
- **R**ead: Retrieve and display existing data (e.g., showing a list of products).
- **U**pdate: Modify existing data (e.g., editing a profile).
- **D**elete: Remove data (e.g., deleting a comment).

### Example 1: To-Do List App
- **Create**: Add a new task to the list.
- **Read**: View the list of tasks.
- **Update**: Edit a task's name or status (e.g., mark as complete).
- **Delete**: Remove a task from the list.

### Example 2: Student Management App
- **Create**: Add a new student record.
- **Read**: Display all student records.
- **Update**: Edit a student's details (e.g., name or grade).

- **Delete**: Remove a student from the system.


import React, { useState } from "react";

const TodoApp = () => {
  const [tasks, setTasks] = useState([]); // For storing tasks
  const [newTask, setNewTask] = useState(""); // For creating new tasks

  // Functions for CRUD operations
  const createTask = () => {
    if (newTask) {
      setTasks([...tasks, { id: Date.now(), name: newTask }]);
      setNewTask("");
    }
  };

  const readTasks = () => tasks;

  const updateTask = (id, updatedName) => {
    setTasks(tasks.map(task => (task.id === id ? { ...task, name: updatedName } : task)));
  };

  const deleteTask = (id) => {
    setTasks(tasks.filter(task => task.id !== id));
  };

  return (
    <div>
      <h1>To-Do List</h1>
      {/* Create */}
      <input
        type="text"
        value={newTask}
        onChange={(e) => setNewTask(e.target.value)}
        placeholder="New Task"
      />
      <button onClick={createTask}>Add Task</button>

      {/* Read */}
      <ul>
        {readTasks().map((task) => (
          <li key={task.id}>
            {task.name}
            {/* Update */}
            <button onClick={() => updateTask(task.id, prompt("Edit Task:", task.name))}>
              Edit
            </button>
            {/* Delete */}
            <button onClick={() => deleteTask(task.id)}>Delete</button>
          </li>
        ))}
      </ul>
    </div>
  );
};

export default TodoApp;


Enter fullscreen mode Exit fullscreen mode
What Each Function Does:
Create: Adds a new task to the tasks array.

const createTask = () => {
  if (newTask) {
    setTasks([...tasks, { id: Date.now(), name: newTask }]);
    setNewTask("");
  }
};


Read: Simply reads the tasks array to display data.


const readTasks = () => tasks;
Update: Finds a task by id and updates its name.


const updateTask = (id, updatedName) => {
  setTasks(tasks.map(task => (task.id === id ? { ...task, name: updatedName } : task)));
};
Delete: Removes a task from the tasks array by id.


const deleteTask = (id) => {
  setTasks(tasks.filter(task => task.id !== id));
};


How It Works:

Add Task: Type in the input box and click "Add Task" to add a new task.

Edit Task: Click "Edit" to prompt for a new name for the task.
Delete Task: Click "Delete" to remove the task.


Enter fullscreen mode Exit fullscreen mode

1. Create Function
Purpose: Adds a new item to the list.
Code:
jsx
Copy code
const createItem = () => {
  if (input) {
    setItems([...items, { id: Date.now(), name: input }]); // Add new item with a unique ID
    setInput(""); // Clear the input field
  }
};
How It Works:
Checks if the input is not empty.
Creates a new object with id and name.
Updates the state using setItems.
2. Read Function
Purpose: Displays the list of items.
Code:
jsx
Copy code
const readItems = () => items; // Simply returns the array of items

return (
  <ul>
    {readItems().map((item) => (
      <li key={item.id}>{item.name}</li>
    ))}
  </ul>
);
How It Works:
Maps through the items array to render each item.
3. Update Function
Purpose: Edits an existing item by id.
Code:
jsx
Copy code
const updateItem = (id) => {
  const newName = prompt("Edit Item:", items.find((item) => item.id === id).name);
  if (newName) {
    setItems(items.map((item) => (item.id === id ? { ...item, name: newName } : item)));
  }
};
How It Works:
Finds the item with the matching id.
Prompts the user for a new name.
Updates the name property of the specific item in the array.
4. Delete Function
Purpose: Removes an item from the list by id.
Code:
jsx
Copy code
const deleteItem = (id) => {
  setItems(items.filter((item) => item.id !== id));
};
How It Works:
Filters the items array to exclude the item with the matching id.
Updates the state with the new array.
Example Usage in the App:
Create: Click the "Add" button after typing an item.

Calls createItem().
Read: Automatically displays the list.

Uses readItems() in the map function.
Update: Click the "Edit" button next to an item.

Calls updateItem(id) for the selected item.
Delete: Click the "Delete" button next to an item.

Calls deleteItem(id) for the selected item.
Complete List of Functions:
jsx
Copy code
const createItem = () => { /* Add a new item */ };
const readItems = () => items; /* Return all items */
const updateItem = (id) => { /* Edit item by ID */ };
const deleteItem = (id) => { /* Remove item by ID */ };








Enter fullscreen mode Exit fullscreen mode

Top comments (0)