How to Build a Simple CRUD App with Next.js

Reading Time: 5 min read

Introduction

Next.js is a powerful framework for building server-rendered React applications. In this post, we'll create a simple CRUD (Create, Read, Update, Delete) app using Next.js.

Setting Up

First, set up a new Next.js project:

npx create-next-app crud-app
cd crud-app
npm run dev

Your new Next.js app will be running at http://localhost:3000.

For more information on setting up a Next.js project, refer to the Next.js documentation.

Creating the CRUD Operations

  1. Create: Add a form to create new items.
  2. Read: Display a list of items.
  3. Update: Add a feature to update existing items.
  4. Delete: Add a feature to delete items.

Example Code

Here's a snippet for adding a new item:

import { useState } from 'react'
 
function AddItem() {
  const [item, setItem] = useState('')
 
  const handleSubmit = (e) => {
    e.preventDefault()
    // Add item to list
  }
 
  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={item}
        onChange={(e) => setItem(e.target.value)}
      />
      <button type="submit">Add Item</button>
    </form>
  )
}
 
export default AddItem

To display the list of items, you can use a simple component like this:

import { useState } from 'react'
 
function ItemList() {
  const [items, setItems] = useState(['Item 1', 'Item 2', 'Item 3'])
 
  return (
    <ul>
      {items.map((item, index) => (
        <li key={index}>{item}</li>
      ))}
    </ul>
  )
}
 
export default ItemList

To update an item, you might have a component like this:

import { useState } from 'react'
 
function UpdateItem({ item, onUpdate }) {
  const [newItem, setNewItem] = useState(item)
 
  const handleSubmit = (e) => {
    e.preventDefault()
    onUpdate(newItem)
  }
 
  return (
    <form onSubmit={handleSubmit}>
      <input
        type="text"
        value={newItem}
        onChange={(e) => setNewItem(e.target.value)}
      />
      <button type="submit">Update Item</button>
    </form>
  )
}
 
export default UpdateItem

And to delete an item, you can use this:

function DeleteItem({ item, onDelete }) {
  return <button onClick={() => onDelete(item)}>Delete</button>
}
 
export default DeleteItem

Running the Application

To run your Next.js application, use the following command:

npm run dev

This will start the development server and your application will be accessible at http://localhost:3000.

For more details on running and building Next.js applications, refer to the Next.js documentation on deployment.

Conclusion

Next.js makes it easy to build robust CRUD applications with server-side rendering, providing a great user experience and SEO benefits. By combining these simple components, you can create a fully functional CRUD application.

Go back Home.