Todo list
Certainly! Below you'll find a basic example of a To-Do List application using React with TypeScript. This application includes the ability to add, remove, and toggle the completion status of tasks.
import React, { useState } from 'react';
type Task = {
id: number;
text: string;
isCompleted: boolean;
};
const ToDoListApp: React.FC = () => {
const [tasks, setTasks] = useState<Task[]>([]);
const [taskInput, setTaskInput] = useState('');
const handleAddTask = () => {
if (taskInput.trim() !== '') {
const newTask: Task = {
id: Math.random(), // not ideal for real applications due to possible collisions
text: taskInput,
isCompleted: false,
};
setTasks([...tasks, newTask]);
setTaskInput('');
}
};
const handleToggleTaskCompletion = (taskId: number) => {
const updatedTasks = tasks.map(task =>
task.id === taskId ? { ...task, isCompleted: !task.isCompleted } : task
);
setTasks(updatedTasks);
};
const handleRemoveTask = (taskId: number) => {
const updatedTasks = tasks.filter(task => task.id !== taskId);
setTasks(updatedTasks);
};
return (
<div>
<h1>To-Do List</h1>
<input
type="text"
value={taskInput}
onChange={(e) => setTaskInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleAddTask()}
/>
<button onClick={handleAddTask}>Add Task</button>
<ul>
{tasks.map(task => (
<li key={task.id} style={{ textDecoration: task.isCompleted ? 'line-through' : 'none' }}>
{task.text}
<button onClick={() => handleToggleTaskCompletion(task.id)}>
{task.isCompleted ? 'Undo' : 'Complete'}
</button>
<button onClick={() => handleRemoveTask(task.id)}>Remove</button>
</li>
))}
</ul>
</div>
);
};
export default ToDoListApp;
This code snippet creates a functional component ToDoListApp
with the following features:
- A form with an input field to type the name of the new task and a button to add it to the list.
- The
tasks
state variable is an array that holds the current list of tasks. - Each task is an object with an
id
,text
, andisCompleted
property. - The
handleAddTask
function adds a new task to the list. - The
handleToggleTaskCompletion
function toggles the completion status of a task. - The
handleRemoveTask
function removes a task from the list.
The input field uses taskInput
as its value, and it updates taskInput
on every change. When the user presses the "Enter" key or clicks the "Add Task" button, the new task is added to the list if the input is not empty. Each task in the list has a "Complete" or "Undo" button to toggle its completion status and a "Remove" button to delete it from the list. Completed tasks are visually indicated with a line-through text decoration.
Creating a To-Do list application with React and TypeScript involves several steps. Here's how to build one step by step:
Step 1: Initialize Project Setup
- Create a new React project with TypeScript (if you haven’t done so already).
- Use create-react-app with TypeScript template or set up your configuration if preferred.
Step 2: Define Task Type
- Define a TypeScript
interface
ortype
for the task object that will include properties likeid
,text
, andisCompleted
.
Step 3: Set Up State
- Use the
useState
hook to set up state variables for the list of tasks and the current input for the new task.
Step 4: Create Input Handlers
- Create a handler function to update the task input state as the user types into the input field.
- Create another handler to add the new task to the list of tasks when the user submits.
Step 5: Implement Task List Rendering
- Use the
map
function to iterate over the tasks array and render each task. - Display tasks with conditional styling based on their completion status.
Step 6: Add Task Completion Toggle
- Create a function that toggles the
isCompleted
property of a task. - This function should identify the task by its
id
, toggle itsisCompleted
status, and update the state.
Step 7: Implement Task Deletion
- Create a function that removes a task from the list.
- This function should filter out the task by its
id
and update the state with the new list.
Step 8: Handle Form Submission
- Implement form submission handling to allow adding tasks by pressing the “Enter” key or clicking an “Add” button.
Step 9: Add Basic Styling
- Add simple CSS or inline styles to make the list readable and visually distinguish between completed and pending tasks.
Step 10: Clean Up and Testing
- Test all functionalities: adding tasks, toggling their completion status, and removing tasks.
- Refactor any code if necessary and ensure that the state updates correctly.
Step 11: Optional Features
- Implement persistent storage (like saving to
localStorage
) so the list doesn’t reset when the app is reloaded. - Add more features such as task editing, prioritization, or categorization.
Step 12: Final Review
- Review the app for any potential bugs or improvements.
- Make sure the app is responsive and provides a good user experience.
By following these steps, you’ll create a basic yet functional to-do list application in React using TypeScript.