Next.js Dynamic Routes: Nested Routes with Folder Structure

Next.js Dynamic Routes: Nested Routes with Folder Structure

"Next.js Dynamic Routes"

  • Next.js' file-system-based router simplifies route organization by organizing folders as route segments, allowing for logical and intuitive URLs. It also supports nested routes, automatic routing, simplified development, SEO benefits, code splitting, and server-side rendering (SSR) support.

  • This approach enhances website performance and allows developers to create dynamic and nested routes while maintaining code organization and SEO benefits.

  • In Next.js, Dynamic Routes allow you to create pages with paths that depend on external data. This feature is useful when you want to generate pages based on dynamic content, such as blog posts, product pages, user profiles, etc. Dynamic Routes are denoted by placing brackets [ ] around a parameter in the page's filename.

  • Next.JavaScript is known as "dynamic routes" because it enables developers to design sites that can accept dynamic or changeable URL components known as route parameters.

  • These route parameters can change, and the same page can provide different content depending on their settings.

  • In a traditional website, each page has a defined URL, and you must develop distinct pages for different types of content.

Example 1: Create a virtual library on a single page that displays a large selection of books

With Next.js, a sophisticated web development framework that enables dynamic and interactive web pages, let us create a Book Library. Creating a virtual library on a single page that displays a large selection of books, each with its card. In dynamic routing will create a smooth experience and how to design adaptable and responsive websites.

First, create a Next.js app using the App Router:

npx create-next-app my-book-library
cd my-book-library
npm run dev
Open http://localhost:3000 from your browser.

This will create an app folder structure like this:

.
└── app
   ├── pages
   │   └── _app.js
   └── components

Next, create a feature folder for your book library:

.
└── app
   ├── pages
   │   └── _app.js
   ├── components
   └── book-library

Within the book-library folder, you can organize your routes and components related to the book library feature:

.
└── app
   ├── pages
   │   └── _app.js
   ├── components
   └── book-library
      ├── Books.jsx      
      ├── BookDetails.jsx
      └── components
         ├── BookCard.jsx
         └── BookList.jsx

_app.js: This is the Next.js Book App component that wraps all other components. You can use it to add global styles, and layouts, or perform actions on every page.

// pages/_app.js
import '../styles/globals.css';

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

export default MyApp;

BookList.js: This component will display a list of books in the book library.

// components/BookList.jsx
import React from 'react';
import BookCard from './BookCard';

const BookList = ({ books }) => {
  return (
    <div>
      <h2>Book Library</h2>
      {books.map((book) => (
        <BookCard key={book.id} book={book} />
      ))}
    </div>
  );
};

export default BookList;

BookCard.js: This component represents a card for each book in the book list.

// components/BookCard.jsx
import React from 'react';

const BookCard = ({ book }) => {
  return (
    <div>
      <h3>{book.title}</h3>
      <p>Author: {book.author}</p>
      <p>Genre: {book.genre}</p>
    </div>
  );
};

export default BookCard;

Books.js: This page will be responsible for fetching the list of books and displaying them using the BookList component.

// pages/book-library/Books.jsx
import React from 'react';
import BookList from '../../components/BookList';

const books = [
  { id: 1, title: 'Book 1', author: 'Author 1', genre: 'Fiction' },
  { id: 2, title: 'Book 2', author: 'Author 2', genre: 'Mystery' },
  { id: 3, title: 'Book 3', author: 'Author 3', genre: 'Adventure' },
];

const Books = () => {
  return (
    <div>
      <h1>Welcome to the Book Library</h1>
      <BookList books={books} />
    </div>
  );
};

export default Books;

BookDetails.jsx will show the details of a specific book:

// pages/book-library/BookDetails.jsx
import React from 'react';
import { useRouter } from 'next/router';

const books = [
  { id: 1, title: 'Book 1', author: 'Author 1', genre: 'Fiction', description: 'A wonderful story...' },
  { id: 2, title: 'Book 2', author: 'Author 2', genre: 'Mystery', description: 'A thrilling mystery...' },
  { id: 3, title: 'Book 3', author: 'Author 3', genre: 'Adventure', description: 'An exciting adventure...' },
];

const BookDetails = () => {
  const router = useRouter();
  const { bookId } = router.query;
  const book = books.find((book) => book.id === parseInt(bookId));

  if (!book) {
    return <div>Book not found</div>;
  }

  return (
    <div>
      <h1>{book.title}</h1>
      <p>Author: {book.author}</p>
      <p>Genre: {book.genre}</p>
      <p>Description: {book.description}</p>
    </div>
  );
};

export default BookDetails;

A Simple Example of a Dynamic Route for Displaying Information about Different Users.

Step 1: To Create a Next.js project

First, ensure that Node.js and npm are installed. Then, run the following instructions to start a new Next.js project:

npx create-next-app my-dynamic-users-app
cd my-dynamic-users-app

Step 2: Creating a Dynamic Page

Create a new folder called "users" under the "pages" folder in the Next.js project. Make a new file called "[username].js" within that folder. The inclusion of "[username]" in the filename indicates that this page will accept dynamic URLs depending on the "username" argument.

- pages
  - users
    - [username].js

Step 3: Fetching Dynamic Data

import { useRouter } from 'next/router';

const UserPage = ({ user }) => {
  const router = useRouter();
  const { username } = router.query;

  return (
    <div>
      <h1>{user.name}</h1>
      <p>Username: {user.username}</p>
      <p>Email: {user.email}</p>
    </div>
  );
};

export default UserPage;

export async function getServerSideProps({ params }) {

  const listOfUsers = {
    john_doe: { name: 'John Doe', username: 'john_doe', email: 'john@example.com' },
    jane_smith: { name: 'Jane Smith', username: 'jane_smith', email: 'jane@example.com' },
    mike_wilson: { name: 'Mike Wilson', username: 'mike_wilson', email: 'mike@example.com' },
  };

  const user = listOfUsers[params.username] || null;

  return {
    props: {
      user,
    },
  };
}

To extract the username parameter from the URL, we utilize the useRouter hook from Next.js. Then, using the params.username, we retrieve data for the specified user in the getServerSideProps method.

Step 4: Try By Yourself

Run your Next.js app using npm run dev, and then navigate to URLs like /users/john_doe, /users/jane_smith, or /users/mike_wilson to visit various user pages. The same page template will be utilized, but the content will be dynamically changed based on the dynamic "username" option, allowing you to show information about various people without having to create individual pages for each. To extract the username parameter from the URL, we utilize the useRouter hook from Next.js. Then, using the params.username, we retrieve data for the specified user in the getServerSideProps method.

This adaptability enables developers to build more scalable and efficient websites. It eliminates the need for duplicating code and makes managing several pages easier.

💡
Next.js's dynamic routes feature makes it easier to create websites with changeable content and improved user experiences. It's the equivalent of having a single page that can "dynamically" modify its content based on what the user wants, making it dynamic.

to be continued .............

Get ready to explore the cutting-edge world of Next.js dynamic routes! Our series of blogs aims to provide insightful information, professional viewpoints, and helpful advice to keep you ahead in the ever-changing landscape of web development. We'll share the latest trends, empowering you to make informed decisions and stay at the forefront of this dynamic environment. Stay tuned for valuable insights and practical tips in our Next.js dynamic route series.

We are looking forward to your participation in our next posts.

Warm regards,

ByteScrum Blog Team,

ByteScrum Technologies Private Limited! 🙏

Did you find this article valuable?

Support ByteScrum Technologies by becoming a sponsor. Any amount is appreciated!