Build this to-do-list app with React! ☝
Table of Contents
Introduction
In this tutorial, you will learn how to build a simple to-do list app using React with the useState hook. This project is perfect for beginners looking to strengthen their React skills and impress potential employers. By the end of this guide, you'll have a fully functional to-do list application.
Step 1: Set Up Your React Environment
To get started, you need to set up your development environment.
- Ensure you have Node.js installed on your machine.
- Create a new React application using the following command:
npx create-react-app todo-list-app - Navigate into your project folder:
cd todo-list-app - Start the development server:
npm start
Step 2: Create the HTML Structure
Next, you will create the basic structure of your to-do list app.
- Open the
src/App.jsfile. - Replace the existing code with the following to set up the structure:
import React, { useState } from 'react'; function App() { const [todos, setTodos] = useState([]); const [inputValue, setInputValue] = useState(''); const handleInputChange = (e) => { setInputValue(e.target.value); }; const handleAddTodo = () => { if (inputValue.trim()) { setTodos([...todos, inputValue]); setInputValue(''); } }; return ( <div> <h1>To-Do List</h1> <input type="text" value={inputValue} onChange={handleInputChange} placeholder="Add a new task" /> <button onClick={handleAddTodo}>Add</button> <ul> {todos.map((todo, index) => ( <li key={index}>{todo}</li> ))} </ul> </div> ); } export default App;
Step 3: Style Your App with CSS
Now, let's add some basic styles to make your app visually appealing.
- Open the
src/App.cssfile. - Add the following CSS to style your to-do list app:
body { font-family: Arial, sans-serif; background-color: #f4f4f4; margin: 0; padding: 20px; } h1 { color: #333; } input { padding: 10px; margin-right: 10px; } button { padding: 10px; } ul { list-style-type: none; padding: 0; } li { background: #fff; padding: 10px; margin: 5px 0; border-radius: 5px; }
Step 4: Implement JavaScript Functions
In this step, we will ensure that the essential functions for adding tasks are working correctly.
- Make sure you have the following functions in your
Appcomponent:handleInputChange: Updates the state with the user's input.handleAddTodo: Adds the new task to the list if the input is not empty.
Tips
- Validate user input to avoid empty tasks.
- Use unique keys for each item in the list to help React identify which items have changed.
Conclusion
You've successfully built a simple to-do list app using React and the useState hook. This project not only helps you practice React fundamentals but also serves as a great portfolio piece. As next steps, consider adding features such as task completion status, editing tasks, or even saving tasks to local storage. Happy coding!