Skip to content

Instantly share code, notes, and snippets.

@ixtk
Created November 15, 2023 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ixtk/0e342f5e312eb97ed38f6c9945e448c5 to your computer and use it in GitHub Desktop.
Save ixtk/0e342f5e312eb97ed38f6c9945e448c5 to your computer and use it in GitHub Desktop.
import "./App.css"
import { useState } from "react"
function App() {
const [todoText, setTodoText] = useState("")
const [todoList, setTodoList] = useState([
{ value: "do homework", isChecked: true, id: 0 },
{ value: "watch a movie", isChecked: false, id: 1 },
{ value: "make bed", isChecked: true, id: 2 }
])
/*
- Add todo
- reset input
- Completed state
- Delete todo
STATE:
- input
- todo list
- completed
*/
const addTodo = () => {
setTodoText("abc")
const newTodo = {
value: todoText,
isChecked: false
}
setTodoList([...todoList, newTodo])
}
const completeTodo = (id) => {
const newTodos = todoList.map((todo) => {
if (todo.id === id) {
// update todo
return { ...todo, isChecked: !todo.isChecked }
}
return todo
})
setTodoList(newTodos)
// state is readonly
// todoList[id].isChecked = true
// todoList.push()
}
const deleteTodo = (id) => {
setTodoList(???)
}
const todos = todoList.map((todo, todoIndex) => {
const elementClass = todo.isChecked ? "todo-completed" : ""
return (
<li className={elementClass} key={todoIndex}>
<span className="todo-text">{todo.value}</span>
<button onClick={() => completeTodo(todo.id)}>Check</button>
<button onClick={() => deleteTodo(todo.id)}>Delete</button>
</li>
)
})
return (
<div style={{ fontFamily: "sans-serif" }}>
<h1>Todos</h1>
<input
type="text"
onChange={(event) => setTodoText(event.target.value)}
value={todoText}
placeholder="Type something..."
/>
<button onClick={addTodo}>Add</button>
<ul>{todos}</ul>
</div>
)
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment