nextjs
  1. nextjs-route-groups

Next.js Route Groups

Introduction

Next.js is a popular and powerful server-side rendering framework for React. It provides several features and functionalities to develop modern web applications quickly. One of the most important features is the ability to group and organize routes in a simple and intuitive way.

Syntax

Next.js provides an API to define routes that can be grouped and organized easily. The syntax for creating route groups in Next.js is as follows:

// pages/index.js
import { useRouter } from 'next/router'
import Link from 'next/link'

const Index = () => {
  const router = useRouter()

  return (
    <>
      <ul>
        <li>
          <Link href="/dashboard/profile">
            <a>Profile</a>
          </Link>
        </li>
        <li>
          <Link href="/dashboard/settings">
            <a>Settings</a>
          </Link>
        </li>
      </ul>
    </>
  )
}

export default Index

// pages/dashboard/profile.js
const Profile = () => {
  return (
    <>
      <h1>Profile Page</h1>
    </>
  )
}

export default Profile

// pages/dashboard/settings.js
const Settings = () => {
  return (
    <>
      <h1>Settings Page</h1>
    </>
  )
}

export default Settings

Explanation

In the above example, a route group has been created in Next.js for the dashboard section of the application. Two routes are defined under this group - /dashboard/profile and /dashboard/settings. The Link component is used to create links to these pages, while the useRouter hook is used to access the current route and its associated properties.

Use

Next.js route groups are useful for organizing and grouping related pages and components together in a structured manner. This can help improve the overall maintainability and readability of the codebase, especially in larger applications.

Important Points

  • Next.js route groups are defined in the pages folder of a Next.js application.
  • A route group can have one or more child routes that are defined as separate files within the group folder.
  • Child routes within a route group can access the properties of the parent route and the Next.js router using hooks and APIs provided by Next.js.

Summary

Next.js route groups provide a simple and intuitive way to organize and structure the routes of a Next.js application. By using this feature, it's possible to improve the maintainability and scalability of the codebase, resulting in a more efficient and effective development process.

Published on: