In the fast-paced world of web development, creating interactive and dynamic user interfaces is crucial. One of the best ways to learn the ropes of modern web frameworks is by building practical projects. This article will guide you, step-by-step, through creating a simple yet functional To-Do List application using Next.js, a powerful React framework.
Why Build a To-Do List App?
The To-Do List app is a classic project for beginners and a great exercise for intermediate developers. It allows you to grasp fundamental concepts like:
- State management
- Event handling
- Component composition
- Data persistence (even in its simplest form)
It’s a project that is easily understood, yet complex enough to solidify your understanding of how to build interactive web applications. Furthermore, it provides a solid foundation for more complex projects you might undertake in the future.
Prerequisites
Before diving into the code, ensure you have the following:
- Node.js and npm (or yarn) installed on your system.
- A basic understanding of HTML, CSS, and JavaScript.
- A code editor (like VS Code) for writing and editing your code.
Setting Up Your Next.js Project
Let’s get started by creating a new Next.js project. Open your terminal and run the following command:
npx create-next-app my-todo-app
This command will set up a new Next.js project named “my-todo-app”. Navigate into your project directory:
cd my-todo-app
Now, start the development server:
npm run dev
This will start the development server, and you can access your application in your web browser at http://localhost:3000 (or the port specified in your terminal).
Project Structure
Your project directory should look something like this:
my-todo-app/
├── node_modules/
├── pages/
│ ├── _app.js
│ └── index.js
├── public/
├── .gitignore
├── next.config.js
├── package-lock.json
├── package.json
└── README.md
The `pages` directory is where you’ll create your pages. `index.js` is the main page of your application. We’ll be working primarily within the `pages/index.js` file for this project.
Building the To-Do List Components
1. Creating the Task Input Component
First, let’s create a component for adding new tasks. Open `pages/index.js` and replace the existing code with the following:
import { useState } from 'react';
function TaskInput({ onAddTask }) {
const [taskText, setTaskText] = useState('');
const handleInputChange = (e) => {
setTaskText(e.target.value);
};
const handleAddTask = () => {
if (taskText.trim() !== '') {
onAddTask(taskText);
setTaskText('');
}
};
return (
<div>
<input
type="text"
value={taskText}
onChange={handleInputChange}
placeholder="Add a task..."
/>
<button onClick={handleAddTask}>Add</button>
</div>
);
}
export default TaskInput;
This component uses the `useState` hook to manage the input field’s value. It takes an `onAddTask` prop, which is a function that will be called when the user clicks the
