Created
September 30, 2021 16:27
-
-
Save abhisheks-12/fd5e296274df3b7fd7e2706f22cd6618 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "./App.css"; | |
import { useState } from "react"; | |
function App() { | |
const [todo, setTodo] = useState(""); | |
const [allTodo, setAllTodo] = useState([]); | |
const [editId, setEditId] = useState(0); | |
const handelSubmit = (e) => { | |
e.preventDefault(); | |
if (editId) { | |
const editTodo = allTodo.find((i) => i.id === editId); | |
const updateTodo = allTodo.map((t) => | |
t.id === editTodo.id | |
? (t = { id: t.id, todo }) | |
: { id: t.id, todo: t.todo } | |
); | |
setAllTodo(updateTodo); | |
setEditId(0); | |
setTodo(""); | |
return; | |
} | |
if (todo !== "") { | |
setAllTodo([{ id: `${Date.now()}`, todo }, ...allTodo]); | |
setTodo(""); | |
} | |
}; | |
const handelDelete = (id) => { | |
const delteArray = allTodo.filter((todo) => todo.id !== id); | |
setAllTodo([...delteArray]); | |
setTodo(""); | |
}; | |
const handelEdit = (id) => { | |
const editArray = allTodo.find((todo) => todo.id === id); | |
setTodo(editArray.todo); | |
setEditId(id); | |
}; | |
return ( | |
<div className="App"> | |
<div className="todo-container"> | |
<h1>Todo App</h1> | |
<form className="todo-form" onSubmit={handelSubmit}> | |
<input | |
type="text" | |
value={todo} | |
onChange={(e) => setTodo(e.target.value)} | |
></input> | |
<button type="submit">{editId ? "Edit" : "Add"}</button> | |
</form> | |
<ul className="all-list"> | |
{allTodo.map((list) => ( | |
<li className="single-list"> | |
<span className="todo-text" id={list.id}> | |
{list.todo} | |
</span> | |
<button onClick={() => handelEdit(list.id)}>Edit</button> | |
<button onClick={() => handelDelete(list.id)}>Delete</button> | |
</li> | |
))} | |
</ul> | |
</div> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment