Modified stock app to Todolist app

master
Jason Zhu 2023-03-01 15:47:24 +11:00
parent a7ae56f99d
commit c816eebbe5
2 changed files with 91 additions and 18 deletions

View File

@ -1,24 +1,66 @@
import React from 'react';
import logo from './logo.svg';
import React, {useState} from 'react';
import './App.css';
import Todo from "./Todo";
interface TodoItem {
id: number;
text: string;
completed: boolean;
}
function App() {
const [todos, setTodos] = useState<TodoItem[]>([]);
const [text, setText] = useState("");
const handleAddTodo = () => {
if (text.trim() === "") return;
const newTodo: TodoItem = {
id: todos.length + 1,
text: text,
completed: false,
};
setTodos([...todos, newTodo]);
setText("");
}
const handleToggleTodo = (id: number) => {
const updatedTodos = todos.map((todo) => {
if (todo.id === id) {
return { ...todo, completed: !todo.completed };
}
return todo;
});
setTodos(updatedTodos);
}
const handleDeleteTodo = (id: number) => {
const updatedTodos = todos.filter((todo) => todo.id !== id);
setTodos(updatedTodos);
}
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.tsx</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
<div>
<h1>Todo List</h1>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
/>
<button onClick={handleAddTodo}>Add Todo</button>
<ul>
{todos.map((todo) => (
<Todo
key={todo.id}
id={todo.id}
text={todo.text}
completed={todo.completed}
onToggle={handleToggleTodo}
onDelete={handleDeleteTodo}
/>
))}
</ul>
</div>
);
}

31
src/Todo.tsx 100644
View File

@ -0,0 +1,31 @@
import React from "react";
interface TodoProps {
id: number;
text: string;
completed: boolean;
onToggle: (id: number) => void;
onDelete: (id: number) => void;
}
const Todo = ( { id, text, completed, onToggle, onDelete }: TodoProps) => {
const handleToggle = () => {
onToggle(id);
};
const handleDelete = () => {
onDelete(id);
};
return (
<li>
<input type="checkbox" checked={completed} onChange={handleToggle} />
<span style={{ textDecoration: completed ? "line-through" : "none"}}>
{text}
</span>
<button onClick={handleDelete}>Delete</button>
</li>
);
};
export default Todo;