how to create edit | delete | add new data function in react.js
Tags: javascript, react, webdev, beginners
Published: 2024-03-26 12:57:43


This code represents a simple Task Manager application built using React. Here's a breakdown of what the code does:

```js
import React, { useState } from 'react';
import './App.css';

function App() {
  const [tasks, setTasks] = useState([]);
  const [taskName, setTaskName] = useState('');
  const [taskEmail, setTaskEmail] = useState('');
  const [taskPhone, setTaskPhone] = useState('');
  const [taskType, setTaskType] = useState('');
  const [editTaskId, setEditTaskId] = useState(null);

  const handleChange = (event) => {
    const { name, value } = event.target;
    switch (name) {
      case 'name':
        setTaskName(value);
        break;
      case 'email':
        setTaskEmail(value);
        break;
      case 'phone':
        setTaskPhone(value);
        break;
      case 'type':
        setTaskType(value);
        break;
      default:
        break;
    }
  };

  const handleSubmit = (event) => {
    event.preventDefault();
    if (taskName.trim() !== '' && taskEmail.trim() !== '' && taskPhone.trim() !== '' && taskType.trim() !== '') {
      if (editTaskId !== null) {
        const updatedTasks = tasks.map(task => {
          if (task.id === editTaskId) {
            return {
              ...task,
              name: taskName,
              email: taskEmail,
              phone: taskPhone,
              type: taskType
            };
          }
          return task;
        });
        setTasks(updatedTasks);
        setEditTaskId(null);
      } else {
        const newTask = {
          id: Date.now(),
          name: taskName,
          email: taskEmail,
          phone: taskPhone,
          type: taskType
        };
        setTasks([...tasks, newTask]);
      }
      setTaskName('');
      setTaskEmail('');
      setTaskPhone('');
      setTaskType('');
    }
  };

  const handleEdit = (id) => {
    const taskToEdit = tasks.find(task => task.id === id);
    if (taskToEdit) {
      setTaskName(taskToEdit.name);
      setTaskEmail(taskToEdit.email);
      setTaskPhone(taskToEdit.phone);
      setTaskType(taskToEdit.type);
      setEditTaskId(id);
    }
  };

  const handleDelete = (id) => {
    setTasks(tasks.filter(task => task.id !== id));
    if (editTaskId === id) {
      setEditTaskId(null);
    }
  };

  return (
    <div className="container">
      <h1>Task Manager</h1>
      <form onSubmit={handleSubmit}>
        <input 
          type="text" 
          name="name"
          placeholder="Name" 
          value={taskName} 
          onChange={handleChange} 
        />
        <input 
          type="email" 
          name="email"
          placeholder="Email" 
          value={taskEmail} 
          onChange={handleChange} 
        />
        <input 
          type="tel" 
          name="phone"
          placeholder="Phone" 
          value={taskPhone} 
          onChange={handleChange} 
        />
        <select 
          name="type" 
          value={taskType} 
          onChange={handleChange}
        >
          <option value="">Select Type</option>
          <option value="Personal">Personal</option>
          <option value="Work">Work</option>
          <option value="Other">Other</option>
        </select>
        <button type="submit">{editTaskId !== null ? 'Update Task' : 'Add Task'}</button>
      </form>
      <ul>
        {tasks.map(task => (
          <li key={task.id}>
            <div>
              <strong>Name:</strong> {task.name}<br />
              <strong>Email:</strong> {task.email}<br />
              <strong>Phone:</strong> {task.phone}<br />
              <strong>Type:</strong> {task.type}
            </div>
            <div>
              <button onClick={() => handleEdit(task.id)}>Edit</button>
              <button onClick={() => handleDelete(task.id)}>Delete</button>
            </div>
          </li>
        ))}
      </ul>
    </div>
  );
}

```

##1. Imports:
 The code imports necessary modules from React and a CSS file ('./App.css'). 
##2. Functional Component Definition:
The `App()` function is a React functional component that represents the main application. It uses React's `useState` hook to manage state within the component.

##2. State Variables:
The component initializes several state variables using `useState`:

- **tasks**: An array to store the list of tasks.
- **taskName, taskEmail, taskPhone, taskType**: Individual state variables to store task details (name, email, phone, type) entered by the user.
- **editTaskId**: A state variable to track the ID of the task being edited.

## 3.Event Handlers:
- **handleChange:** This function is called when input fields change. It updates the corresponding state variables based on the input field's name.
- **handleSubmit:** This function is called when the form is submitted (either to add a new task or update an existing one). It performs validation checks and updates the tasks array accordingly.
- **handleEdit:** This function is called when the user clicks on the `"Edit"` button for a task. It populates the form fields with the details of the task being edited.
- **handleDelete:** This function is called when the user clicks on the `"Delete"` button for a task. It removes the task from the tasks array.

##4. Render Function:

- The `render()` function returns JSX representing the UI of the Task Manager application.
- It consists of a form where users can input task details (`name`, `email`, `phone`, `type`) and buttons to add or update tasks.
- Below the form, there's a list of tasks displayed as `<li>` elements.
- Each task displays its details (name, email, phone, type) along with "Edit" and "Delete" buttons.
##6. Export: The App component is exported as the default export, making it available for use in other parts of the application.

Overall, this code creates a Task Manager application where users can add, edit, and delete tasks, with task details being stored and managed using React's state.

##7. CSS (style)
**App.css**

```css
.container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: #f9f9f9;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h1 {
  text-align: center;
  margin-bottom: 20px;
}

form {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  margin-bottom: 20px;
}

input[type="text"],
input[type="email"],
input[type="tel"],
select {
  width: calc(50% - 10px);
  padding: 10px;
  margin-bottom: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 16px;
}

select {
  width: 100%;
}

button {
  width: 100%;
  padding: 10px 20px;
  background-color: #007bff;
  border: none;
  border-radius: 5px;
  color: #fff;
  cursor: pointer;
  font-size: 16px;
}

ul {
  list-style-type: none;
  padding: 0;
}

li {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  border-bottom: 1px solid #ccc;
}

li:last-child {
  border-bottom: none;
}

button {
  background-color: #dc3545;
  border-radius: 5px;
  border: none;
  color: #fff;
  padding: 5px 10px;
  cursor: pointer;
}

@media screen and (max-width: 600px) {
  form {
    flex-direction: column;
  }

  input[type="text"],
  input[type="email"],
  input[type="tel"],
  select {
    width: 100%;
  }
}

```

##summry:
This code defines a React functional component called `App` which serves as a Task Manager application. It utilizes React's state management with the `useState` hook to handle task data. The component allows users to input task details such as name, email, phone, and type, and provides functionality to add, edit, and delete tasks. It includes event handlers for form submission, editing tasks, and deleting tasks. The UI consists of a form for inputting task details and a list of tasks displayed with their details and corresponding edit and delete buttons. Overall, the code provides a basic Task Manager interface with CRUD (Create, Read, Update, Delete) operations for managing tasks.

[github](https://github.com/04anilr)
[website](https://my-portfolio-two-lemon-36.vercel.app/)


[Array methods in react.js ](https://dev.to/04anilr/how-to-use-array-methods-in-real-project-example-add-new-record-3o82)
[Fragment in react.js](https://dev.to/04anilr/fragment-in-reactjs-example-of-fragment-299a) 
[Conditional rendering in react.js](https://dev.to/04anilr/conditional-rendering-in-react-conditional-rendering-example-in-react-3j46)
[Children component in react.js](https://dev.to/04anilr/methods-of-react-children-component-in-react-4ol7)
[use of Async/Await in react.js](https://dev.to/04anilr/how-to-use-asyncawait-3a3o)
[Array methods in react.js](https://dev.to/04anilr/array-methods-in-reactjs-36jb)
[JSX in react.js](https://dev.to/04anilr/jsx-in-reactjs-3f7o)
[Event Handling in react.js](https://dev.to/04anilr/event-handling-in-react-5hc7)
[Arrow function in react.js](https://dev.to/04anilr/arrow-functions-in-react-4gb2)
[Virtual DOM in react.js](https://dev.to/04anilr/how-to-work-virtual-dom-in-react-dom-1b39)
[React map() in react.js](https://dev.to/04anilr/how-to-create-react-map-24pp)
[How to create dark mode in react.js](https://dev.to/04anilr/how-to-create-dark-mode-in-react-js-2kn2)
[How to use of Props in react.js](https://dev.to/04anilr/props-and-state-with-example-1bl1)
[Class component and Functional component](https://dev.to/04anilr/class-component-functional-component-in-react-k43)
[How to use of Router in react.js](https://dev.to/04anilr/how-to-use-of-router-in-reactreact-router-1163)
[All React hooks explain ](https://dev.to/04anilr/react-hooks-cheat-sheet-2hic)
[CSS box model ](https://dev.to/04anilr/css-box-model-work-2k0a)
[How to make portfolio nav-bar in react.js](https://dev.to/04anilr/how-to-make-nav-bar-for-portfolio-website-365m)