Skip to main content

Building a Simple Todo App with Next.js and Context API

Next.js offers an efficient way to build server-side rendered React applications with improved performance and SEO benefits. Combining it with the Context API allows you to manage global state effectively, enhancing the user experience. In this blog post, we'll guide you through creating a simple todo app using Next.js and Context API, demonstrating the key functionalities and providing code examples.


Prerequisites

Before we start, ensure you have the following prerequisites:

  • Basic understanding of HTML, CSS, and JavaScript
  • Familiarity with React JS concepts
  • Node.js and npm installed on your system


Project Setup

Create a new Next.js project using npx:


npx create-next-app todo-app


cd todo-app

Install the necessary dependencies:


npm install


Setting Up Context API

Create a new file named TodoContext.js in the src directory. This file will house the context provider and consumer components.

Inside TodoContext.js, define the initial state and functions for interacting with the todo list:



import React, { createContext, useState } from 'react';


const TodoContext = createContext();


const TodoProvider = ({ children }) => {

  const [todos, setTodos] = useState([]);


  const addTodo = (text) => {

    setTodos([

      ...todos,

      { id: Date.now(), text: text, completed: false },

    ]);

  };


  const toggleTodo = (id) => {

    setTodos(

      todos.map((todo) =>

        todo.id === id ? { ...todo, completed: !todo.completed } : todo

      )

    );

  };


  const deleteTodo = (id) => {

    setTodos(todos.filter((todo) => todo.id !== id));

  };


  return (

    <TodoContext.Provider

      value={{

        todos,

        addTodo,

        toggleTodo,

        deleteTodo,

      }}

    >

      {children}

    </TodoContext.Provider>

  );

};


export { TodoContext, TodoProvider };


This code defines the initial state as an empty array and provides functions for adding, toggling completion, and deleting todos.


Implementing the Todo List

Create a new file named TodoList.js in the pages directory. This component will display the todo list and its functionalities.

Inside TodoList.js, import the context and use it to access the state and functions:



import React, { useContext } from 'react';

import { TodoContext } from '../src/TodoContext';


const TodoList = () => {

  const { todos, addTodo, toggleTodo, deleteTodo } = useContext(TodoContext);


  const handleAddTodo = (event) => {

    event.preventDefault();

    const text = event.target.elements.todoInput.value;

    if (text.trim()) {

      addTodo(text);

      event.target.elements.todoInput.value = '';

    }

  };


  return (

    <div className="todo-list">

      <h1>Todo List</h1>

      <form onSubmit={handleAddTodo}>

        <input type="text" name="todoInput" placeholder="Enter todo" />

        <button type="submit">Add</button>

      </form>

      <ul>

        {todos.map((todo) => (

          <li key={todo.id} className={todo.completed ? 'completed' : ''}>

            <input

              type="checkbox"

              checked={todo.completed}

              onChange={() => toggleTodo(todo.id)}

            />

            <span>{todo.text}</span>

            <button onClick={() => deleteTodo(todo.id)}>Delete</button>

          </li>

        ))}

      </ul>

    </div>

  );

};


export default TodoList;


This code renders the todo list and provides forms for adding and deleting todos. It also allows users to toggle the completion status of individual items.


Wrapping the App

In pages/_app.js, import the TodoProvider and wrap the entire application with it:


import React from 'react';

import { TodoProvider } from '../src/TodoContext';

import '../styles/globals.css';


function MyApp({ Component, pageProps }) {

  return (

    <TodoProvider>

      <Component {...pageProps} />

    </TodoProvider>

  );

}


export default MyApp;


This ensures that the entire application has access to the todo context and its functionalities.


Run the App

Start the development server:


npm run dev

Open http://localhost:3000 in your browser to view the running application.


Conclusion

This simple todo app demonstrates the effective use of Next.js and Context API in building client-side rendered applications. By separating the state logic from the presentation components, you improve code organization and ensure better maintainability 

Comments

Archive

Show more

Topics

Show more