Creating a To-Do List App with Next.js


Introduction

Building a To-Do List App is a great way to learn the fundamentals of web development with Next.js. In this tutorial, we will create a simple To-Do List application using Next.js, a popular React framework. This app will allow users to add, edit, and delete tasks. Let's get started!


Setting Up the Project

First, make sure you have Node.js and npm installed on your system. If not, you can download and install them from the official website.


Create a new Next.js project using the following commands:


        npx create-next-app todo-list-app
cd todo-list-app

Creating Components

In Next.js, you can create reusable components to build your application. Let's create two components: one for the To-Do List and another for individual tasks.


        // components/TodoList.js
import React from 'react';
const TodoList = ({ tasks }) => (
<ul>
{tasks.map((task, index) => (
<li key={index}>{task}</li>
))}
</ul>
);
export default TodoList;

        // components/Task.js
import React from 'react';
const Task = ({ task, onDelete }) => (
<div>
{task}
<button onClick={onDelete}>Delete</button>
</div>
);
export default Task;

State Management

To manage the state of our To-Do List, we can use the React state. We'll maintain an array of tasks that can be added, edited, or deleted.


        import React, { useState } from 'react';
import TodoList from '../components/TodoList';
import Task from '../components/Task';
export default function Home() {
const [tasks, setTasks] = useState([]);
const [taskInput, setTaskInput] = useState('');
const addTask = () => {
if (taskInput.trim() !== '') {
setTasks([...tasks, taskInput]);
setTaskInput('');
}
};
const deleteTask = (index) => {
const updatedTasks = tasks.filter((_, i) => i !== index);
setTasks(updatedTasks);
};
return (
<div>
<h2>To-Do List</h2>
<div>
<input
type="text"
value={taskInput}
onChange={(e) => setTaskInput(e.target.value)}
/>
<button onClick={addTask}>Add</button>
</div>
<TodoList tasks={tasks} />
{tasks.map((task, index) => (
<Task key={index} task={task} onDelete={() => deleteTask(index)} />
))}
</div>
);
}

Conclusion

Congratulations! You've just created a simple To-Do List App using Next.js. This is just the beginning, and you can further enhance this app by adding features like task editing, task completion, and data persistence. It's a great project to help you learn more about React and Next.js.