Learn Remix Β· 2/13

Routing Fundamentals: Navigating the App

7 min read

Routing Fundamentals: Navigating the App πŸ—ΊοΈ

Welcome, intrepid coder, to the foundational pillar of any web application: routing! In the world of Remix, we're leaving the chaotic days of manually configuring every single URL path behind. Instead, we'll embark on a journey through a file-based system that's as intuitive as organizing files on your computer.

At its core, routing is the mechanism that maps a URL in the browser to the specific code that should be executed to render a page. Imagine you're a librarian. A visitor comes to you with a specific book request (the URL). Your job is to know exactly which aisle and shelf (the file) to go to to find that book. Remix's routing system is your library's intuitive organizational system.

The problem that file-based routing solves is the often complex and error-prone process of manually defining every route in a central configuration file. This can become a nightmare to manage as an application grows. With Remix, the file structure is the route structure, making it easy to understand, maintain, and scale.


1. File-Based Routing: Mapping URLs to Files πŸ“‚

Definition: File-based routing is a convention where the file and folder structure within a designated routes directory directly corresponds to the URL paths of your application.

The Problem: In many traditional web frameworks, you'd have a separate configuration file where you would manually map URL strings to specific components. This can be tedious, and it's easy to make a typo or for the configuration to get out of sync with your actual component files.

The Solution: Remix elegantly solves this by saying, "Your file system is your routing configuration." If you want a page at /about, you simply create a file named about.tsx inside the app/routes directory. It's that simple!

Let's see this in action. Imagine this file structure:

nix
app/
└── routes/
    β”œβ”€β”€ _index.tsx
    └── about.tsx
  • app/routes/_index.tsx will correspond to the root URL: /. The underscore in _index.tsx is a special convention for the default or "index" page of a directory.
  • app/routes/about.tsx will map to the URL: /about.

Under the Hood: When a request comes into the Remix server, it looks at the URL path and then searches for a corresponding file in the app/routes directory to handle that request.

A funny little thought: Imagine if your file cabinet at home worked this way. To find your car's title, you'd just yell "CAR TITLE!" and the right drawer would just pop open. That's the kind of magic Remix brings to routing.


2. Nested Routing: Layouts and the <Outlet /> Component nesting-doll

Definition: Nested routing allows you to create layouts that are shared across multiple pages by nesting routes within one another. The <Outlet /> component is a placeholder that tells a parent route where to render its child routes.

The Problem: Think about a typical website. You often have a consistent header, footer, and maybe a sidebar that appears on every page. Without nested routing, you would need to import and render these layout components on every single page, leading to a lot of code duplication.

The Solution: Remix's nested routing allows a parent route to define a layout, and then child routes are rendered within that layout. This is where the magical <Outlet /> component comes in.

Consider this file structure for a blog:

applescript
app/
└── routes/
    β”œβ”€β”€ blog.tsx
    └── blog.my-first-post.tsx

Here's how you would structure the blog.tsx file to act as a layout:

tsx
// app/routes/blog.tsx
import { Outlet } from "@remix-run/react";

export default function BlogLayout() {
  return (
    <div>
      <h1>My Awesome Blog</h1>
      <main>
        <Outlet /> {/* Child routes will be rendered here */}
      </main>
    </div>
  );
}

And the blog.my-first-post.tsx:

tsx
// app/routes/blog.my-first-post.tsx
export default function MyFirstPost() {
  return (
    <article>
      <h2>My First Post</h2>
      <p>This is the content of my very first blog post!</p>
    </article>
  );
}

When a user navigates to /blog/my-first-post, Remix will first render the BlogLayout component. When it encounters the <Outlet />, it will then render the MyFirstPost component in its place. The result is a seamless page with the shared layout and the specific content of the child route.

Real-life analogy: Think of a picture frame (the parent layout). The <Outlet /> is the empty space in the middle. You can swap out different photos (the child routes) without having to change the frame itself.


3. Dynamic Route Segments: Handling IDs and Slugs πŸ†”

Definition: Dynamic route segments are parts of a URL that can change, often used for things like product IDs or blog post slugs. In Remix, you create a dynamic segment by prefixing a filename with a $ sign.

The Problem: Imagine you're building an e-commerce site with thousands of products. It would be completely impractical to create a separate file for every single product page. You need a way to create a template for a product page that can display different information based on the product ID in the URL.

The Solution: Remix's dynamic routes are the answer. By using a file name like products.$productId.tsx, you're telling Remix that the part of the URL that corresponds to $productId can be anything.

Let's look at an example file structure:

nix
app/
└── routes/
    └── products.$productId.tsx

Now, inside products.$productId.tsx, you can access the value of productId from the URL using the useParams hook from Remix:

tsx
// app/routes/products.$productId.tsx
import { useParams } from "@remix-run/react";

export default function Product() {
  const { productId } = useParams();

  return <h1>Product Details for ID: {productId}</h1>;
}

If a user navigates to /products/123, the productId will be "123". If they go to /products/abc, the productId will be "abc". This allows you to have a single component that can render an infinite number of product pages.

Industry Practice: This is incredibly common for any application that deals with lists of items where each item has its own detail page, such as e-commerce products, blog posts, user profiles, and so on.


4. Index Routes: Designing the Default View for Nested Layouts 🏠

Definition: An index route is the default route that is rendered for a nested layout when the URL matches the parent route's path exactly. You create an index route by naming a file _index.tsx within a directory that shares the same name as a layout route, or by using a dot notation like parent._index.tsx.

The Problem: Let's go back to our blog example. We have a layout at /blog and a specific post at /blog/my-first-post. But what should be displayed when a user navigates to just /blog? Without an index route, they would see the layout with an empty space where the <Outlet /> is, which isn't very user-friendly.

The Solution: You can create an index route to define the content that should be displayed within a layout's <Outlet /> when no other child route is active.

Here are two common ways to create an index route for our /blog layout:

Option 1: Folder and _index.tsx

nix
app/
└── routes/
    └── blog/
        └── _index.tsx

Option 2: Dot Notation

nix
app/
└── routes/
    β”œβ”€β”€ blog.tsx
    └── blog._index.tsx

Both of these structures will result in blog._index.tsx (or blog/_index.tsx) being rendered inside the blog.tsx layout's <Outlet /> when the user visits /blog.

Here's what the content of blog._index.tsx might look like:

tsx
// app/routes/blog._index.tsx
export default function BlogIndex() {
  return (
    <div>
      <h2>Welcome to our blog!</h2>
      <p>Select a post from the list to read.</p>
    </div>
  );
}

Now, when a user goes to /blog, they'll see the blog layout with this welcoming message. When they navigate to /blog/my-first-post, the content of blog._index.tsx will be replaced by the content of blog.my-first-post.tsx.

Key Takeaway: Index routes are crucial for providing a good user experience with nested layouts, as they ensure that there's always meaningful content being displayed.


πŸ“š Extra Reading & References

Challenge

You are tasked with creating the component code for a basic e-commerce site's product section using Remix's file-based routing conventions. You will write the code for four separate route files within a single editor. Assume all necessary imports from '@remix-run/react' and 'react' are available.

Your task is to implement the following route components:

  1. app/routes/_index.tsx: The home page component. It should simply display a welcome message.
  2. app/routes/products.tsx: A parent layout component for all product-related pages. This component should display a main heading for the products section and provide a space for child routes to render.
  3. app/routes/products._index.tsx: The index page for the /products URL. It should display a list of links to two sample product detail pages.
  4. app/routes/products.$productId.tsx: A dynamic route component to display details for a specific product. It must retrieve the product's ID from the URL and display it.

Expected result

Your final code should consist of four separate default-exported function components, one for each specified file path.

  1. app/routes/_index.tsx:

    • A default exported function component named HomePage.
    • It should return a single <h1> element with the text "Welcome to the Store!".
  2. app/routes/products.tsx:

    • A default exported function component named ProductsLayout.
    • It must import Outlet from @remix-run/react.
    • It should return a div containing an <h2> with the text "Our Products" followed by the <Outlet /> component.
  3. app/routes/products._index.tsx:

    • A default exported function component named ProductsIndex.
    • It must import Link from @remix-run/react.
    • It should return a div with a <h3> saying "Browse our selection" and an unordered list (<ul>) containing two list items (<li>).
    • Each list item should contain a <Link> component pointing to /products/widget-a and /products/gizmo-b respectively.
  4. app/routes/products.$productId.tsx:

    • A default exported function component named ProductDetail.
    • It must import and use the useParams hook to extract the productId from the URL.
    • It should return a div containing an <h4> that displays the text "Details for Product: " followed by the retrieved productId.
javascript

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.