import React, { useState } from "react"; const App = () => { const [list, setList] = useState([]); const [input, setInput] = useState(""); const handleSetInput = (e) => { setInput(e.target.value); }; const addTodo = (todo) => { const newTodo = { id: Math.random(), todo: todo, completed: false, }; setList([...list, newTodo]); setInput(""); }; const handleAddClick = () => { addTodo(input); }; const handleToggleComplete = (id) => { setList((prevList) => prevList.map((todo) => { if (todo.id === id) { return { ...todo, completed: !todo.completed }; } return todo; }) ); }; const handleDelete = (id) => { const filtered = list.filter((todo) => todo.id !== id); setList(filtered); }; return ( <div> <h1>Todo List</h1> <input type="text" value={input} onChange={handleSetInput} /> <button onClick={handleAddClick}>Add</button> <ul> {list.map((todo) => ( <li key={todo.id}> <input type="checkbox" checked={todo.completed} onChange={() => handleToggleComplete(todo.id)} /> <span style={{ textDecoration: todo.completed ? "line-through" : "none", }} > {todo.todo} </span> {todo.completed && ( <button onClick={() => handleDelete(todo.id)}>×</button> )} </li> ))} </ul> </div> ); }; export default App;
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter