Using Child routes with React Router

 

Modern way to do React Router:

(Note I am using React-router-dom 6.10) Using Child routes can greatly enhance the organization, maintainability, and functionality of your routing configuration. Here's why and how to use child routes.


1) Nested Layouts:

Child routes let you set up nested layouts. For example, if you have a main layout like HomeLayout that includes shared elements (like a header, footer, or navigation bar), you can use child routes to nest different pages within this layout.


In this example, HomeLayout will render for all the child routes (Landing, Register, Login). 


2) index property: 

Child routes let you set a default route for a layout, which is great for defining a landing page for a section of your app. In the example above, Landing will be the default if the user goes to the root path ('/'). Just make sure you add <Outlet /> to the parent element <HomeLayout /> to display all the child routes like in the example below.



3) Nested Layouts:

Child routes let you set different error boundaries for different parts of your app. In the first example, the errorElement at the root route level handles errors for all the nested routes. So if the user types in a wrong route, the <Error /> page will render.


4) Cleaner Code:

Using child routes keeps your routing setup organized and easier to manage. Instead of having a long list of routes, you can group related ones together, which is super helpful for larger apps.

Comments

Popular posts from this blog

Lifecycle of React components

Styled Components

e-commerce website built with React.nodejs