0
0
RemixHow-ToBeginner ยท 4 min read

How to Create Nested Routes in Remix: Simple Guide

In Remix, create nested routes by organizing files in nested folders inside the routes directory. Use index.tsx for default child routes and layout files like layout.tsx to share UI across nested routes.
๐Ÿ“

Syntax

Remix uses the file system to define routes. Nested routes are created by placing route files inside folders within the routes directory. A folder represents a parent route, and files inside it represent child routes.

Use index.tsx inside a folder to define the default child route. Use layout.tsx (previously __layout.tsx) to create a shared layout for all nested routes.

plaintext
routes/
  โ”œโ”€โ”€ dashboard/
  โ”‚    โ”œโ”€โ”€ layout.tsx
  โ”‚    โ”œโ”€โ”€ index.tsx
  โ”‚    โ””โ”€โ”€ settings.tsx
  โ””โ”€โ”€ index.tsx
๐Ÿ’ป

Example

This example shows a dashboard route with nested routes for the main dashboard page and settings page. The layout.tsx file wraps both child routes with shared UI like a header.

tsx
/* routes/dashboard/layout.tsx */
import { Outlet } from "@remix-run/react";

export default function DashboardLayout() {
  return (
    <div>
      <header><h1>Dashboard</h1></header>
      <main>
        <Outlet />
      </main>
    </div>
  );
}

/* routes/dashboard/index.tsx */
export default function DashboardIndex() {
  return <p>Welcome to your dashboard!</p>;
}

/* routes/dashboard/settings.tsx */
export default function DashboardSettings() {
  return <p>Change your settings here.</p>;
}

/* routes/index.tsx */
export default function Home() {
  return <p>Home page</p>;
}
Output
Home page Dashboard Welcome to your dashboard! Dashboard Change your settings here.
โš ๏ธ

Common Pitfalls

  • Not using Outlet in layout files causes nested routes not to render.
  • Missing index.tsx in a folder means no default child route.
  • Incorrect folder or file names break route matching.
tsx
/* Wrong: Missing Outlet in layout */
export default function Layout() {
  return <div><h1>Title</h1></div>;
}

/* Right: Include Outlet to render children */
import { Outlet } from "@remix-run/react";
export default function Layout() {
  return (
    <div>
      <h1>Title</h1>
      <Outlet />
    </div>
  );
}
๐Ÿ“Š

Quick Reference

Summary tips for nested routes in Remix:

  • Use folders inside routes to nest routes.
  • Use index.tsx for default child routes.
  • Use layout.tsx for shared UI with Outlet.
  • Always import and use Outlet to render nested content.
  • Match folder and file names exactly for routing to work.
โœ…

Key Takeaways

Create nested routes by placing route files inside folders in the routes directory.
Use layout files with Outlet to share UI across nested routes.
Always include an index.tsx file for default child routes.
Folder and file names must match route paths exactly.
Missing Outlet in layouts prevents nested routes from rendering.