DEV Community

Cover image for how to create edit | delete | add new data function in react.js
Anil
Anil

Posted on

how to create edit | delete | add new data function in react.js

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

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>
  );
}

Enter fullscreen mode Exit fullscreen mode

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

.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%;
  }
}

Enter fullscreen mode Exit fullscreen mode

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
website

Array methods in react.js
Fragment in react.js
Conditional rendering in react.js
Children component in react.js
use of Async/Await in react.js
Array methods in react.js
JSX in react.js
Event Handling in react.js
Arrow function in react.js
Virtual DOM in react.js
React map() in react.js
How to create dark mode in react.js
How to use of Props in react.js
Class component and Functional component
How to use of Router in react.js
All React hooks explain
CSS box model
How to make portfolio nav-bar in react.js

Top comments (0)