0Pricing
Next.js 15 Fullstack Web Apps · Урок

Вложенные макеты и группы маршрутов

Структурируйте приложение с помощью вложенных макетов и организуйте маршруты в группы для лучшей модульности.

«Вложенные макеты и группы маршрутов» — бесплатный урок Next.js 15 Fullstack Web Apps на CoddyKit. Это урок 2 из 4. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения Next.js 15 Fullstack Web Apps, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Nested Layouts: Shared UI

Welcome! In this lesson, we'll explore two powerful App Router features: Nested Layouts and Route Groups.

Nested layouts allow you to share UI components (like headers, sidebars, or footers) across multiple pages within a specific segment of your application. This helps maintain consistency and reduces code duplication.

How Layouts Work

In Next.js 15 App Router, layouts are defined by creating a layout.tsx file inside a folder.

  • A layout component receives a children prop, which will be the content of the nested route segments (e.g., page.tsx or other nested layouts).
  • Layouts are rendered hierarchically, meaning an outer layout wraps an inner layout.

The Root Layout

Every Next.js App Router project must have a Root Layout. This is the top-most layout.tsx file located directly in your app/ directory.

  • It defines the essential <html> and <body> tags.
  • It applies to all routes in your application.

Root Layout Code

Here's a basic example of the required root layout. Notice how it takes children as a prop.

import './globals.css';

export default function RootLayout({ children }) {
  return (
    <html lang="en">
      <body>
        {children}
      </body>
    </html>
  );
}

Creating a Nested Layout

To create a nested layout, simply add another layout.tsx file inside a subfolder within your app/ directory.

For example, app/dashboard/layout.tsx would create a layout specific to all routes under /dashboard.

Nested Layout Code Example

This example shows a DashboardLayout that wraps its content, adding a navigation bar specific to the dashboard section. The DashboardPage will be rendered within this layout.

// app/dashboard/layout.tsx
export default function DashboardLayout({ children }) {
  return (
    <section>
      <nav>
        <h1>Dashboard Nav</h1>
      </nav>
      {children}
    </section>
  );
}

// app/dashboard/page.tsx
export default function DashboardPage() {
  return (
    <div>
      <h2>Welcome to Dashboard</h2>
      <p>This content is inside the DashboardLayout.</p>
    </div>
  );
}

Introducing Route Groups

Route Groups are folders in your app/ directory that don't affect the URL path. They are primarily used for:

  • Organizing routes into logical groups.
  • Applying specific layouts to a subset of routes without changing the URL.

You define a route group by wrapping the folder name in parentheses, like (groupName).

Why Use Route Groups?

Route groups are incredibly useful for:

  • Separate Layouts: Easily apply a unique layout to a specific group of pages (e.g., an (auth) group with a login layout).
  • Project Organization: Keep related routes together for better maintainability.
  • Excluding Segments: Prevent a folder name from appearing in the URL path.

Route Group Layout Example

Here, a (marketing) route group contains its own layout. Any page within this group (like /about) will use this layout, but the URL remains /about, not /marketing/about.

// app/(marketing)/layout.tsx
export default function MarketingLayout({ children }) {
  return (
    <>
      <header>
        <h1>Marketing Site</h1>
      </header>
      <main>
        {children}
      </main>
      <footer>
        <p>&copy; 2024 Marketing</p>
      </footer>
    </>
  );
}

// app/(marketing)/about/page.tsx
export default function AboutPage() {
  return (
    <div>
      <h2>About Us</h2>
      <p>Learn more about our company.</p>
    </div>
  );
}

Layouts & Groups Check

Consider the following Next.js App Router structure:

app/
├── layout.tsx
├── dashboard/
│   ├── layout.tsx
│   └── settings/
│       └── page.tsx
└── (auth)/
    └── login/
        └── page.tsx

Which layout.tsx files would apply to the app/dashboard/settings/page.tsx route?

Recap: Layouts & Groups

You've learned about structuring your Next.js application using Nested Layouts and Route Groups!

  • Nested Layouts (`layout.tsx`) allow you to share UI components across segments of your app, creating a consistent user experience.
  • Route Groups (`(folder)`) help organize your file structure and apply specific layouts to groups of routes without affecting the URL path.

These features are crucial for building scalable and maintainable Next.js applications!

Часто задаваемые вопросы

Урок «Вложенные макеты и группы маршрутов» бесплатный?

Да — полный текст урока «Вложенные макеты и группы маршрутов» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс Next.js 15 Fullstack Web Apps, подпишись на CoddyKit PRO. Курс Next.js 15 Fullstack Web Apps содержит 4 уроков всего.

Чему я научусь в уроке «Вложенные макеты и группы маршрутов»?

Структурируйте приложение с помощью вложенных макетов и организуйте маршруты в группы для лучшей модульности. Ты практикуешь Next.js 15 Fullstack Web Apps с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать Next.js 15 Fullstack Web Apps?

Предыдущий опыт не требуется. Next.js 15 Fullstack Web Apps на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 2 из 4.

Сколько времени занимает урок «Вложенные макеты и группы маршрутов»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке Next.js 15 Fullstack Web Apps?

Да. Каждый урок Next.js 15 Fullstack Web Apps включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Динамические маршруты и сегменты catch-all
  2. Вложенные макеты и группы маршрутов
  3. Параллельные и перехватывающие маршруты
  4. Соглашения для интерфейсов загрузки и ошибок
← Назад к Next.js 15 Fullstack Web Apps