React Router Tutorial
People new to react generally don't know how to structure their routes.
Beginners and entry level developers will...
For further actions, you may consider blocking this person and/or reporting abuse
What's the cleanest way to pass props into the route element in the pagesData.tsx file? This was the quick fix that VS Code applied, but it seems messy:
this will depend on the arguments of the *Blog *. If they are required I suggest:
This is much better, thanks! What would you suggest for redirects with this method? Say, for example, if I want to redirect the path from the default "/", to "/home".
You can do like this for less than v5 version
<Switch>
<Redirect exact from="/" to="/home"/>
</Switch>
Or for newest v6
<Route path="/" element={<Navigate to="/home" replace />} />
I really liked your article. Its a topic that needs to be talked about more.
Anyways my only thoughts were to make this lazy.
Then code-splitting can happen and we see big reductions in bundle sizes.
you can do it like this
const pagesData: routerType[] = [
{
path: "",
element: React.lazy(() => import('./Home')),
title: "home"
},
{
path: "about",
element: React.lazy(() => import('./About')),
title: "about"
}
];
Interesting way to structure it!
One thing i didn't understand. You changed format from JSX to an array of objects when you moved everything out off app.tsx. Combining that with splitting the code up in multiple files; doesn't that make it harder to read?
Hey Johan,
so actually this is the better practice as when you begin to scale the code it makes it more readable, for example if you have 100 routes for your site you can then begin to separate them like so
*Basic pages *
Advance Page
All routes
Now actually the update to react router (which is now v6) makes this format moot. Their new structure is basically the same as the one i've suggested here instead of the JSX format. This makes it more readable when scaling.
Nice way to separate the routes in a single file and organizate it. .
So we have created Types in this to use the routes, but how can we achieve it in javascript?
But how do you handle nested routes?
@kachiic You article helped me. This is how I used your solution for nested routes
router.jsx
pages.jsx
This way I can achieve multi-level nested routing...