Learn how to build a simple and interactive to-do app using React. Step-by-step guide with code examples and best practices.
Table of content
One of the best ways to get comfortable with React is by building a simple to-do app. In this tutorial, you’ll create a fully functional React to-do app from scratch. We’ll cover state management, handling user input, updating lists, and best practices for structuring React components.
npx create-react-app todo-app
to scaffold your project.cd todo-app
and npm start
to run your development server.import React, { useState } from 'react';
import TodoForm from './TodoForm';
import TodoList from './TodoList';
function App() {
const [todos, setTodos] = useState([]);
const addTodo = text => {
setTodos([...todos, { text, completed: false, id: Date.now() }]);
};
const removeTodo = id => {
setTodos(todos.filter(todo => todo.id !== id));
};
return (
<div>
<h1>To-Do App</h1>
<TodoForm addTodo={addTodo} />
<TodoList todos={todos} removeTodo={removeTodo} />
</div>
);
}
export default App;
import React, { useState } from 'react';
function TodoForm({ addTodo }) {
const [value, setValue] = useState('');
const handleSubmit = e => {
e.preventDefault();
if (!value.trim()) return;
addTodo(value);
setValue('');
};
return (
<form onSubmit={handleSubmit}>
<input type="text" value={value} onChange={(e) => setValue(e.target.value)} placeholder="Enter a new task" />
<button type="submit">Add</button>
</form>
);
}
export default TodoForm;
import React from 'react';
import TodoItem from './TodoItem';
function TodoList({ todos, removeTodo }) {
return (
<ul>
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} removeTodo={removeTodo} />
))}
</ul>
);
}
export default TodoList;
import React from 'react';
function TodoItem({ todo, removeTodo }) {
return (
<li>
{todo.text}
<button onClick={() => removeTodo(todo.id)}>Remove</button>
</li>
);
}
export default TodoItem;
localStorage
for persistenceBuilding a to-do app in React is a fantastic way to learn the basics of building components, managing state, and handling events. As you gain confidence, try adding more features to make your app truly unique. Happy coding!