Below is a simple yet robust example of a Todo List application built with React. This application will allow users to:
Add new todos
Mark todos as completed
Delete todos
Filter todos by all, active, or completed
This example assumes you have a basic understanding of React and have Node.js installed on your machine. If you haven't set up a React environment before, you can quickly create one by running npx create-react-app todo-list-app in your terminal, then replace the src folder's content with the code provided below.
Project Structure
After setting up your project (e.g., with create-react-app), your src directory should look like this:
code Copy code
src/
├── components/
│ ├── Todo.js
│ ├── TodoForm.js
│ ├── TodoList.js
│ └── TodoFilters.js
├── App.css
├── App.js
├── index.js
└── index.css
Code
src/components/Todo.js
jsx Copy code
import React from 'react';
// Represents a single Todo item
const Todo = ({ todo, onComplete, onDelete }) => {
return (
<li className={`todo-item ${todo.isCompleted ? 'completed' : ''}`}>
<input
type="checkbox"
checked={todo.isCompleted}
onChange={() => onComplete(todo.id)}
/>
<span>{todo.text}</span>
<button onClick={() => onDelete(todo.id)}>Delete</button>
</li>
);
};
export default Todo;
src/components/TodoForm.js
jsx Copy code
import React, { useState } from 'react';
// Handles adding new Todo items
const TodoForm = ({ onAdd }) => {
const [text, setText] = useState('');
// Handles form submission to add a new Todo
const handleSubmit = (e) => {
e.preventDefault();
if (!text.trim()) return; // Prevents empty todos
onAdd(text);
setText('');
};
return (
<form onSubmit={handleSubmit}>
<input
type="text"
value={text}
onChange={(e) => setText(e.target.value)}
placeholder="Add new todo"
/>
<button type="submit">Add</button>
</form>
);
};
export default TodoForm;
src/components/TodoList.js
jsx Copy code
import React from 'react';
import Todo from './Todo';
// Displays a list of Todo items
const TodoList = ({ todos, onComplete, onDelete }) => {
return (
<ul>
{todos.map((todo) => (
<Todo key={todo.id} todo={todo} onComplete={onComplete} onDelete={onDelete} />
))}
</ul>
);
};
export default TodoList;
src/components/TodoFilters.js
jsx Copy code
import React, { useState } from 'react';
// Handles filtering of Todo items
const TodoFilters = ({ onFilterChange, currentFilter }) => {
const filters = ['all', 'active', 'completed'];
return (
<div>
{filters.map((filter) => (
<button
key={filter}
onClick={() => onFilterChange(filter)}
style={{ fontWeight: currentFilter === filter ? 'bold' : 'normal' }}
>
{filter}
</button>
))}
</div>
);
};
export default TodoFilters;
src/App.js
jsx Copy code
import React, { useState, useEffect } from 'react';
import './App.css';
import TodoForm from './components/TodoForm';
import TodoList from './components/TodoList';
import TodoFilters from './components/TodoFilters';
function App() {
const [todos, setTodos] = useState([]); // State to store Todo items
const [filter, setFilter] = useState('all'); // State for current filter
// Loads todos from localStorage when the app mounts
useEffect(() => {
const storedTodos = localStorage.getItem('todos');
if (storedTodos) setTodos(JSON.parse(storedTodos));
}, []);
// Saves todos to localStorage whenever the todos state changes
useEffect(() => {
localStorage.setItem('todos', JSON.stringify(todos));
}, [todos]);
// Adds a new Todo item
const addTodo = (text) => {
setTodos([...todos, { id: Date.now(), text, isCompleted: false }]);
};
// Toggles the completion status of a Todo
const completeTodo = (id) => {
setTodos(
todos.map((todo) => (todo.id === id ? { ...todo, isCompleted: !todo.isCompleted } : todo))
);
};
// Removes a Todo item
const deleteTodo = (id) => {
setTodos(todos.filter((todo) => todo.id !== id));
};
// Updates the current filter
const filterTodos = (filter) => {
setFilter(filter);
};
// Returns the filtered list of Todo items based on the current filter
const getVisibleTodos = () => {
switch (filter) {
case 'active':
return todos.filter((todo) => !todo.isCompleted);
case 'completed':
return todos.filter((todo) => todo.isCompleted);
default:
return todos;
}
};
return (
<div className="App">
<h1>Todo List</h1>
<TodoForm onAdd={addTodo} />
<TodoFilters onFilterChange={filterTodos} currentFilter={filter} />
<TodoList todos={getVisibleTodos()} onComplete={completeTodo} onDelete={deleteTodo} />
</div>
);
}
export default App;
src/App.css (Basic Styling, feel free to enhance)
css Copy code
.App {
max-width: 400px;
margin: 40px auto;
padding: 20px;
background-color: #f0f0f0;
border: 1px solid #ddd;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.todo-item {
margin-bottom: 10px;
padding: 10px;
background-color: #fff;
border: 1px solid #ccc;
border-radius: 5px;
display: flex;
align-items: center;
}
.todo-item.completed {
text-decoration: line-through;
opacity: 0.7;
}
.todo-item input[type='checkbox'] {
margin-right: 10px;
}
.todo-item button {
margin-left: auto;
background-color: #ff0000;
color: #fff;
border: none;
padding: 5px 10px;
font-size: 12px;
cursor: pointer;
}
.todo-item button:hover {
background-color: #cc0000;
}
/* Additional styling for a modern look */
.todo-item {
transition: all 0.3s ease;
}
.todo-item:hover {
transform: scale(1.01);
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}
Running the Application
Ensure you're in your project directory.
Run npm start or yarn start depending on your package manager.
Open your web browser and navigate to http://localhost:3000.
Example Use Cases
Adding a Todo : Type your task in the input field and click "Add".
Completing a Todo : Check the checkbox next to the todo item.
Deleting a Todo : Click the "Delete" button next to the todo item.
Filtering Todos : Click on "all", "active", or "completed" to filter the list accordingly.
Advanced Features for Senior-Level Implementation
Error Handling : Implement try-catch blocks in critical operations (e.g., when saving to localStorage) to handle potential errors gracefully.
Advanced State Management : Consider using Redux or React Query for more complex state management, especially in larger applications.
Validation : Add input validation to ensure that todos are not empty and meet specific criteria (e.g., length).
Due Dates : Allow users to set due dates for todos and display reminders or notifications.
Prioritization : Introduce a prioritization system (e.g., high, medium, low) to help users focus on critical tasks.
User Authentication : Implement user authentication to allow multiple users to access their own todo lists.
Drag-and-Drop : Add drag-and-drop functionality to enable users to reorder todos based on priority or deadlines.