Tuesday, 29 April 2025

Build a Simple To-Do App with Next.js

 

Step 1: Create the Project

Open your terminal and run:

npx create-next-app@latest nextjs-todo --app --ts
cd nextjs-todo
npm install

When prompted, choose:

  • App Router: Yes

  • Tailwind CSS: Yes

  • TypeScript: Yes


Step 2: Clean Starter Files

Open the project and delete the content of app/page.tsx.


Step 3: Add the To-Do App Code

Replace app/page.tsx with the following code:

'use client';

import { useEffect, useState } from 'react';

export default function Home() {
  const [tasks, setTasks] = useState<string[]>([]);
  const [input, setInput] = useState('');

  useEffect(() => {
    const saved = localStorage.getItem('tasks');
    if (saved) {
      setTasks(JSON.parse(saved));
    }
  }, []);

  useEffect(() => {
    localStorage.setItem('tasks', JSON.stringify(tasks));
  }, [tasks]);

  const addTask = () => {
    if (input.trim() === '') return;
    setTasks([...tasks, input.trim()]);
    setInput('');
  };

  const removeTask = (index: number) => {
    const newTasks = [...tasks];
    newTasks.splice(index, 1);
    setTasks(newTasks);
  };

  return (
    <main className="min-h-screen flex flex-col items-center justify-center bg-gray-100 p-4">
      <h1 className="text-3xl font-bold mb-6">To-Do List</h1>
      <div className="flex gap-2 mb-4">
        <input
          type="text"
          value={input}
          onChange={(e) => setInput(e.target.value)}
          placeholder="Add a new task..."
          className="px-4 py-2 rounded border border-gray-300 focus:outline-none focus:ring"
        />
        <button
          onClick={addTask}
          className="bg-blue-500 text-white px-4 py-2 rounded hover:bg-blue-600"
        >
          Add
        </button>
      </div>

      <ul className="w-full max-w-md space-y-2">
        {tasks.map((task, index) => (
          <li
            key={index}
            className="flex justify-between items-center bg-white px-4 py-2 rounded shadow"
          >
            <span>{task}</span>
            <button
              onClick={() => removeTask(index)}
              className="text-red-500 hover:text-red-700"
            >
              ✕
            </button>
          </li>
        ))}
      </ul>
    </main>
  );
}

Step 4: Confirm Tailwind CSS Setup

Your tailwind.config.ts should already include:

content: [
  './app/**/*.{js,ts,jsx,tsx}',
]

No further changes are needed if you selected Tailwind during setup.


Step 5: Run the App

Run the development server:

npm run dev

Then open your browser at:

http://localhost:3000

The app lets you:

  • Add new tasks

  • Delete tasks

  • Save tasks in local storage (they stay after refresh)

  • Use a clean and responsive UI with Tailwind CSS

No comments:

Post a Comment