Explain Codes LogoExplain Codes Logo

Nested routes with react router v4/v5

javascript
react-router
nested-routes
routing
Anton ShumikhinbyAnton Shumikhin·Nov 22, 2024
TLDR

To create nested routes with React Router v4/v5, encapsulate a <Route> inside another. Define the parent route normally, then nest a child route using match.path for relative paths:

<Route path="/parent" component={Parent} /> // Inside Parent component: <Route path={`${match.path}/child`} component={Child} />

Accessing /parent/child renders Child inside Parent, thus achieving nested rendering.

Taking it to an advanced level, structure nested routes within distinct Components. This, coupled with a Switch, ensures only the first matching Route displays. An upgrade to v6 for superior nested routing might be tempting; familiarize yourself with the con(tricks) of the trade in the new version beforehand.

Structuring Nested Routes

Also known as the MapQuest of our code. Here's how to keep your app's directions tidy:

  • Wrap nested <Routes> in a <Fragment> or a div to define distinctive layouts and styles for different sections.
  • Utilize the <Switch> component to only render the first matching route.
  • Use functional components with the render prop or the children function prop within <Route>. (Pop Quiz: Can you explain inline rendering and why you need access to match?)

It's like the Waze of routing. Use <Link> components and match.url to navigate smoothly even in nested routes:

<Link to={`${match.url}/details`}>View Details</Link>

You're preserving the parent route's path so if the parent forgets where it left its keys (aka changes), links remain consistent.

Route Management: A User Manual

Because having rules is not always a bad thing:

  • Define nested routes before root routes to render them correctly.
  • Use 'exact' on your <Route> components to prevent premature rendering, much like in Hollywood movie plots.
  • Include <Redirect> when necessary. It's like GPS telling you to turn around when you've taken a wrong turn.

Finally, separate frontend and admin areas with unique and correct route paths. It's not just about user experience—it's about clear lines in your app's architecture.

Using Hooks for Routing, Not Just for Hanging Pictures

useRouteMatch isn't just a fancy hook to hang your coat on. It helps you build relative links and gather route match data without prop passing:

let { path, url } = useRouteMatch();

Don't forget to style each section uniquely and let child components have their own nested routing. After all, variety is the spice of coding life.

Leveling Up Your Nesting Game

Using Layouts in Nesting

Consider creating a dedicated layout component. It's like having a wardrobe just for your nested route's outfits:

const ProductsLayout = ({ children }) => ( <div> <Sidebar /> <main>{children}</main> // Look, Mom, no props! </div> ); // Don't forget to use it! <Route path={`${match.path}/products`} component={ProductsLayout}> <Route path={`${match.path}/details`} component={ProductDetails} /> </Route>

Resolving Route Conflict: Not Just a Reality Show

Avoid coming on the DailyWTF with a healthy practice on treating similar routes:

<Switch> <Route path="/products/new" component={NewProduct} /> <Route path="/products/:id/edit" component={EditProduct} /> <Route path="/products/:id" component={ProductDetails} /> <Route path="/products" component={AllProducts} /> </Switch>

Basically, detail first, then generalize. It's like the opposite of creating a machine learning model.

Redirection and Route Guard

Security isn't just about the latest firewall. Consider redirections and route guards for some additional peace of mind:

<Route path="/admin"> {isAdmin ? <AdminPanel /> : <Redirect to="/" />} </Route>