Creating a Todo Application using Next.js

Next.js is a framework for building server-rendered React applications. It provides a powerful set of features for web development such as automatic code splitting, server-side rendering, and static site generation. In this blog post, we will be creating a simple Todo application using Next.js.

Setting up the project

To get started, you will need to have Node.js and npm (or yarn) installed on your machine. Once you have these dependencies set up, you can create a new Next.js project using the following command:

npx create-next-app my-todo-app

This will create a new directory called “my-todo-app” with the basic file structure and dependencies for a Next.js app.

Creating the Todo List component

In this step, we will create a TodoList component that will display a list of todo items. Create a new file called TodoList.js in the components folder and add the following code:

import React from 'react';

const TodoList = ({ todos }) => {
  return (
    <ul>
      {todos.map((todo) => (
        <li key={todo.id}>
          <span>{todo.text}</span>
          <button>Delete</button>
        </li>
      ))}
    </ul>
  );
};

export default TodoList;

In this code, we are rendering an unordered list and mapping over the todos prop to create a list item for each todo item. We also added a button to delete the todo item.

Adding the Todo Form

Now that we have the TodoList component, we need to create a form to add new todo items. Create a new file called TodoForm.js in the components folder and add the following code:

Copy code
import React, { useState } from 'react';

const TodoForm = ({ addTodo }) => {
  const [text, setText] = useState('');

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!text) return;
    addTodo(text);
    setText('');
  };

  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Add Todo..."
      />
    </form>
  );
};

export default TodoForm;


In this code, we are creating a form with an input that allows the user to enter a new todo item. When the form is submitted, it calls the addTodo function with the text of the input as an argument. We are also reset the text state after adding the todo item.

Creating the TodoPage

Create a new file called TodoPage.js in the pages folder and add the following code:

Copy code
import React, { useState } from 'react';
import TodoList from '../components/TodoList';
import TodoForm from '../components/TodoForm';

const TodoPage = () => {
const [todos, setTodos] = useState([]);

const addTodo = (text) => {
setTodos([...todos, { id: todos.length + 1, text }]);
};

const deleteTodo = (id) => {
setTodos(todos.filter((todo) => todo.id !== id));
};

return (
<div>
<TodoForm addTodo={addTodo} />
<TodoList todos={todos} deleteTodo={deleteTodo} />
</div>
);
};

export default TodoPage;


In this file, we are creating a TodoPage component that contains the TodoForm and TodoList components. We are also using React’s useState hook to manage the state of the todo items. The addTodo function is passed down to the TodoForm component as a prop and is called when a new todo item is added. The deleteTodo function is passed down to the TodoList component as a prop and is called when a todo item is deleted.

Adding Routing

Add the following code in your pages/index.js file to redirect users to the TodoPage by default

import TodoPage from './TodoPage';

export default function Home() {
  return <TodoPage />;
}

Now the user will be able to access the TodoPage by visiting the root of your application.

That’s it! You now have a working Todo application built with Next.js. You can customize the application further by adding styles, saving the todo items to a database, or adding more features.

Adding Styles

You can add styles to your Todo application using a CSS preprocessor like SASS or using CSS-in-JS libraries like styled-components.

If you decide to use a CSS preprocessor, you will need to install the necessary dependencies and configure Next.js to use it. You can add the CSS files to the styles directory in the root of your project.

If you prefer to use styled-components, you can install it using npm or yarn by running the following command:

npm install styled-components

And then you can import it in your TodoForm.js and TodoList.js and add styles to your components.

import styled from 'styled-components';

const TodoForm = ({ addTodo }) => {
  // ...
  return (
    <Form onSubmit={handleSubmit}>
      <Input
        type="text"
        value={text}
        onChange={(e) => setText(e.target.value)}
        placeholder="Add Todo..."
      />
    </Form>
  );
};

const Form = styled.form`
  display: flex;
  margin-bottom: 16px;
`;

const Input = styled.input`
  flex: 1;
  padding: 8px;
  border-radius: 4px;
  border: 1px solid #ccc;
`;


Saving Todo items to a database

To save the todo items to a database, you will need to create a backend service that the Next.js app can communicate with. You can use a variety of technologies to build the backend, such as Node.js with Express, Python with Flask or Ruby on Rails.

In your backend service, you will need to create a REST API that the frontend can send requests to for creating, reading, updating, and deleting todo items.

Then you need to call the API in the TodoPage component’s functions like addTodo, deleteTodo to perform the CRUD operations on todo items.

Additionally, you can also use a library like axios or fetch to communicate with the backend service.

In summary, creating a Todo application using Next.js is a straightforward process, but you can also add further functionality like styles, routing, and saving the data to a database. It’s a great way to learn more about building web applications with React and Next.js and you can use the concepts you learn to build more advanced applications in the future.

Advertisement

Getting started with Next.js and code samples.

Introduction

Next.js is a popular framework for building web applications with React. It provides a lot of powerful features out of the box, such as server-rendered React components, automatic code splitting, and easy-to-use development tools. In this blog post, we’re going to take a look at how to get started with Next.js and build a simple web application. By the end of this post, you should have a good understanding of the basic concepts behind Next.js, and be able to start building your own applications with the framework.

Creating a New Next.js Project

The first step in building a Next.js application is to create a new project. You can do this using the Next.js CLI, which can be installed using npm:

npm init next-app my-app

This command will create a new directory called “my-app” that contains the basic file structure for a Next.js application. You should now be able to start the development server by running the following command:

npm run dev

If everything is set up correctly, you should see the message “ready on http://localhost:3000” in your terminal, and be able to view the default “Hello World” Next.js app in your browser.

Understanding the File Structure

Once you have created a new Next.js project, it’s a good idea to take a look at the file structure to understand how the application is organized. The most important directories and files in a Next.js project are:

  • pages/: This directory contains the pages of your web application. Each file in this directory represents a page on your site, and its filename is used as the path for that page. For example, the file pages/about.js represents the “about” page of your site, and can be accessed at the url “/about”.
  • public/: This directory contains files that should be served as-is, such as images and fonts.
  • package.json: This file contains information about your project, such as its dependencies and scripts.
  • next.config.js: This file is used to configure advanced settings for your Next.js application.

Creating a Simple Page

Now that you have a basic understanding of the file structure of a Next.js project, let’s create our first page.

In the pages directory, create a new file called “about.js”. Inside this file, add the following code:

import React from "react";

export default function About() {
  return <h1>About Page</h1>;
}

This is a simple React component that renders an h1 tag with the text “About Page”. Next.js uses the file name of this component to define the path of the page. So, this component will be rendered when the application is accessed at the “/about” path.

If you start the development server with “npm run dev” and access “http://localhost:3000/about” in your browser, you should see the “About Page” text on the page.

Adding Routing

In a more complex application, you’ll likely have more than one page and you’ll need a way to navigate between them. Next.js provides an easy way to do this through the use of dynamic routing.

To add dynamic routing, you’ll need to create a new file in the pages directory, and add a special syntax to the file name.

For example, create a new file called “users/[userId].js”. Inside the file, you can access the userId variable through the useRouter hook from the next/router package and use it to fetch data from an API or display information about a specific user.

import { useRouter } from 'next/router'

export default function User() {
  const router = useRouter()
  const { userId } = router.query

  return <h1>User: {userId}</h1>
}

Now, when you visit the “/users/1” or “/users/2” path, the userId variable will be set to “1” or “2” respectively, and the corresponding user information can be displayed on the page.

To create the navigation links between pages, you can use the Link component from the next/link package.

import Link from 'next/link'

export default function Navigation() {
  return (
    <nav>
      <Link href="/">
        <a>Home</a>
      </Link>
      <Link href="/about">
        <a>About</a>
      </Link>
      <Link href="/users/1">
        <a>User 1</a>
      </Link>
    </nav>
  )
}

Building a Server-rendered React App with Next.js

Next.js also allows you to build server-rendered React apps, which can improve the performance and SEO of your application. To do this, you can use the getServerSideProps function in a page to fetch data on the server and then pass it down to the component as props.

import axios from 'axios'

export default function User({ user }) {
  return <h1>User: {user.name}</h1>
}

export async function getServerSideProps(context) {
  const { userId } = context.params
  const res = await axios.get(`https://my-api.com/users/${userId}`)
  const user = res.data

  return {
    props: {
      user
    }
  }
}


In this example, the getServerSideProps function is making a request to an API to fetch the user data and passing it down to the component as a prop. This way, the user data will be available on the initial render of the component on the server, improving the performance and SEO of your application.

Conclusion

In this blog post, we’ve covered the basics of getting started with Next.js. We’ve looked at how to create a new project, the file structure of a Next.js project, creating a simple page, adding routing, and building a server-rendered React app. With the knowledge from this post, you should be well on your way to building your own web applications with Next.js.

Next.js is a powerful framework that makes it easy to build high-performance web applications. With its built-in features like automatic code splitting, server-rendering, and easy-to-use development tools, it can save you a lot of time and effort compared to building a similar application from scratch. I hope this post has been helpful in getting you started with Next.js, and I encourage you to continue learning more about the framework and experimenting with building your own projects.

To take your Next.js skills to the next level, I recommend checking out the official documentation, which provides a lot of valuable information and examples. Additionally, there are many tutorials and courses available online that can help you learn more about the framework.

Another useful tool that can be used with Next.js is Vercel, it’s a cloud platform for static site generators and serverless functions that can greatly simplify the deployment process of your Next.js application. With Vercel, you can deploy your application with a single command, and it will handle everything from building your application to provisioning the necessary resources.

In addition, there are many libraries and packages that have been built for Next.js, such as next-i18next for internationalization and next-redux for state management. These can greatly enhance the functionality of your application and make development more efficient.

In summary, Next.js is a powerful framework that makes it easy to build high-performance web applications. With its built-in features, it can save you a lot of time and effort. However, if you are just getting started, it can be difficult to know where to start. I hope that this post has provided you with a solid foundation and a good starting point for your Next.js journey.