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.
By the end of this reading, you should be able to:
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:
Home component renders at the / path.TeamsIndex component renders at the /teams path.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:
/teams//teams/1/teams/1/scheduleHowever, a route can only have one * wildcard, and it must be at the end of the path.
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:
TeamsIndex is an index route and renders at /teams.TeamDetails renders at /teams/:teamId.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.
The code above results in the following routes:
Home at /TeamsIndex at /teamsTeamDetails at /teams/:teamIdTo access the :teamId parameter inside the TeamDetails component, use the useParams hook from react-router-dom.
In this reading, you learned:
To deepen your understanding, explore these topics:
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.