avatarMatteo Possamai

Summarize

Building a Simple To-Do Web App with Next.js: A Step-by-Step Tutorial

Dirty your hand with programming projects

Photo by Lina Trochez on Unsplash

Introduction:

In the exciting journey of learning a new programming language or framework, nothing beats the hands-on experience of building a real-world project. Not only does it reinforce your understanding of the technology, but it also provides a tangible showcase for potential employers.

In this comprehensive tutorial, we’ll guide you through the process of creating a simple To-Do web app using Next.js, a powerful React framework. By the end of this tutorial, you’ll have a functional app with a front-end interface and a back-end database. Let’s dive in and get your hands dirty!

Prerequisites

Before we start, make sure you have Node.js and npm (Node Package Manager) installed on your system. You can download them from the official Node.js website.

Step 1: Setting Up the Project

First, let’s create a new Next.js project. Open your terminal and run the following commands:

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

This will set up a new Next.js project called “todo-app.”

Step 2: Creating the Front-End Interface

In this step, we’ll create the user interface for our To-Do app.

  1. Navigate to the pages directory inside your project.
  2. Create a new file called index.js.

Now, let’s write the code for the front-end interface.

import React, { useState } from 'react';

const Home = () => {
  const [tasks, setTasks] = useState([]);
  const [inputValue, setInputValue] = useState('');
  const addTask = () => {
    if (inputValue) {
      setTasks([...tasks, inputValue]);
      setInputValue('');
    }
  };
  const removeTask = (index) => {
    const newTasks = tasks.filter((_, i) => i !== index);
    setTasks(newTasks);
  };
  return (
    <div>
      <h1>My To-Do List</h1>
      <div>
        <input
          type="text"
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
        />
        <button onClick={addTask}>Add Task</button>
      </div>
      <ul>
        {tasks.map((task, index) => (
          <li key={index}>
            {task}
            <button onClick={() => removeTask(index)}>Remove</button>
          </li>
        ))}
      </ul>
    </div>
  );
};
export default Home;

Step 3: Setting Up a Database

Now, let’s set up a simple database using a JSON file to store our tasks. We’ll create a tasks.json file in the root directory of our project.

[]

Step 4: Implementing Backend Logic

In this step, we’ll create APIs to handle tasks using Next.js API routes.

  1. Create a new directory called api in the root of your project.
  2. Inside the api directory, create a new file called tasks.js.

Now, let’s write the code for our API route.

// api/tasks.js
import fs from 'fs';
export default (req, res) => {
  if (req.method === 'GET') {
    const tasks = JSON.parse(fs.readFileSync('./tasks.json', 'utf-8'));
    res.status(200).json(tasks);
  } else if (req.method === 'POST') {
    const { task } = req.body;
    const tasks = JSON.parse(fs.readFileSync('./tasks.json', 'utf-8'));
    tasks.push(task);
    fs.writeFileSync('./tasks.json', JSON.stringify(tasks));
    res.status(201).json({ message: 'Task added successfully' });
  }
};

Step 5: Connecting Frontend and Backend

Let’s connect our front-end interface with the backend API.

  1. In the pages directory, open the index.js file.
  2. Import the useState and useEffect hooks from React.
  3. Modify the Home component to fetch tasks from the backend and update the UI.
// pages/index.js
import React, { useState, useEffect } from 'react';

const Home = () => {
  const [tasks, setTasks] = useState([]);
  const [inputValue, setInputValue] = useState('');
  useEffect(() => {
    fetch('/api/tasks')
      .then((response) => response.json())
      .then((data) => setTasks(data));
  }, []);
  // ... (rest of the component remains unchanged)
};

Conclusion

Congratulations! You’ve successfully built a simple To-Do web app using Next.js. Throughout this tutorial, you’ve learned how to create a front-end interface, set up a basic database, and implement backend logic using Next.js API routes. This hands-on experience will undoubtedly accelerate your learning journey and provide you with a practical project to showcase to potential employers. As you continue to explore and expand your programming skills, remember that the best way to grow is by diving into projects and challenging yourself to apply your knowledge in real-world scenarios.

By following this tutorial, you’ve laid a solid foundation for more advanced web applications and gained valuable insights into Next.js. Happy coding and keep building!

Note: Remember to deploy your app to a hosting service like Vercel or Netlify to make it accessible online and further enhance your portfolio.

In Plain English

Thank you for being a part of our community! Before you go:

Nextjs
JavaScript
Javascript Tips
Programming
Software Development
Recommended from ReadMedium