React Router - Routes

Understanding React Router Routes

React Router allows you to define the routes that you pass to createBrowserRouter in two different ways:

Although React Router does not specify a preference, route objects are the recommended method for defining routes, as they provide a more intrinsic structure for routing.

Learning Goals

By the end of this reading, you should be able to:

Defining Route Objects

createBrowserRouter takes an array of route objects as its argument. The simplest way to define routes for your router is to create an array of these route objects.

A route object is a JavaScript object containing keys such as path, element, and children. For example:


const router = createBrowserRouter([
  {
    path: '/',
    element: 
  },
  {
    path: 'teams',
    element: 
  }
]);
    

In the example above:

Matching Routes to Paths

React Router determines which route to render based on the specificity of the paths. Routes with more specific paths (fewer wildcards) are matched first.

A special wildcard, * (splat), matches anything of any length. For example, /teams/* will match:

However, a route can only have one * wildcard, and it must be at the end of the path.

Defining Nested Routes

Nested routes allow you to structure components hierarchically. For example, suppose TeamsIndex displays a list of teams, and clicking on a team should show details about that team at /teams/:teamId. You can set this up using child routes:


const router = createBrowserRouter([
  {
    path: '/',
    element: 
  },
  {
    path: 'teams',
    children: [
      {
        index: true,
        element: 
      },
      {
        path: ':teamId',
        element: 
      }
    ]
  }
]);
    

In this example:

Relative vs. Absolute Paths

Children paths that do not start with / are relative to their parent. The :teamId path inside the teams route expands to /teams/:teamId.

Paths that begin with / are always absolute. For example, the TeamDetails route above could also be written as:


{
  path: '/teams/:teamId',
  element: 
}
    

Adding a / at the end of a path does not affect functionality. path: 'teams' and path: 'teams/' are equivalent.

Putting It All Together

The code above results in the following routes:

To access the :teamId parameter inside the TeamDetails component, use the useParams hook from react-router-dom.

What You Have Learned

In this reading, you learned:

Further Exploration

To deepen your understanding, explore these topics:

Conclusion

React Router allows you to efficiently manage routing in your applications. By understanding how route objects work and how to construct nested routes, you can create dynamic and structured React apps.