Add-Edit_delete
import React, { useState } from "react";
function App() {
const [tasks, setTasks] = useState([]);
const [newTask, setNewTask] = useState("");
const [isEditing, setIsEditing] = useState(false);
const [currentTaskIndex, setCurrentTaskIndex] = useState(null);
const addTask = () => {
if (newTask.trim()) {
setTasks([...tasks, newTask]);
setNewTask("");
}
};
const editTask = (index) => {
setNewTask(tasks[index]); // Set the current task to the input field
setIsEditing(true);
setCurrentTaskIndex(index);
};
const saveTask = () => {
if (newTask.trim()) {
const updatedTasks = [...tasks];
updatedTasks[currentTaskIndex] = newTask;
setTasks(updatedTasks);
setNewTask("");
setIsEditing(false);
setCurrentTaskIndex(null);
}
};
const removeTask = (index) => {
const updatedTasks = tasks.filter((_, i) => i !== index);
setTasks(updatedTasks);
};
return (
<div style={{ textAlign: "center", marginTop: "50px" }}>
<h1>To-Do List with Edit Feature</h1>
<input
type="text"
value={newTask}
onChange={(e) => setNewTask(e.target.value)}
placeholder="Add or edit a task"
/>
<button onClick={isEditing ? saveTask : addTask}>
{isEditing ? "Save" : "Add"}
</button>
<ul>
{tasks.map((task, index) => (
<li key={index}>
{task}{" "}
<button onClick={() => editTask(index)} style={{ color: "blue" }}>
Edit
</button>{" "}
<button onClick={() => removeTask(index)} style={{ color: "red" }}>
X
</button>
</li>
))}
</ul>
</div>
);
}
export default App;
Comments
Post a Comment