Skip to content
Advertisement

Organizing React routes into separate components

I’m trying to find a way to organize my routes to assist the dev who might be taking over my work in the future. I thought of separating my <Route /> entries into separate components and then just load those into a main component similar to how users are assigned groups.

The issue is that when using more than one component only the first one works. This might not be the most react way of doing this so I’m also open to alternatives.

Original route arrangement

JavaScript

Separating the public routes from the auth ones:

JavaScript

This way I can use it as such:

JavaScript

Flipping <PublicRouteGroup /> and <AuthRouteGroup /> only changes the order:

JavaScript

Update #1

This is thanks to @skyboyer. By moving the <Switch> to the child components and removing it from the AllRoutes component each component started to show. It appears adding the <Switch> in AllRoutes is allowing only the first hit to show which is as <Switch> does. But now by removing it it shows the 404 at the end of each page as well.

Basically, it looks like this:

JavaScript

Advertisement

Answer

It appears this current set up of treating components like OOP classes you can extend from is the wrong approach. I’ve instead made use of arrays since these can be acted upon by the spread operator. It still accomplishes the same goal of organizing routes across an infinite number of groups which was what I was after.

Create the array for each group

JavaScript

Create the routes

JavaScript

I figure this can also be modified further if you’re using nested objects in your array.

I’d like to thank @skyboyer for providing an insight into this problem.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement