Setting up routing in ReactJS is an important step that could be done in a few ways. In this article we are going to see the one I prefer the most, the object-based routing.
Object-based routing gives us the ability to write an object that has a list of the routes and components that will be utilized in the apps that we create. This object is currently going through the process of being “converted” into standard route elements.
Routing Configuration
The first thing, after creating our components, is to create a config file named routes-config.js
:
import About from '../../features/about/about';
import Contact from '../../features/contact/contact';
import Home from '../../features/home/home';
import NotFound from '../../features/not-found/not-found';
import appRoutes from './routes';
const routesConfig = [
{
path: '/home',
element: <Home />,
},
{
path: '/about',
element: <About />,
children: [
{
path: '/about/home',
element: <Home />,
},
],
},
{
path: '/contact',
element: <Contact />,
},
{
path: '*',
element: <NotFound />,
},
];
export default routesConfig;
As you could see in the code, we have created the config array of objects. Every single object in the array can have multiple keys, such as:
- path (path to our route)
- element (a component that is going to be used on that route)
- children (an array of route objects for nesting routes inside our components)
Route Renderer
Here is a tiny component for rendering the routes. We need this component because we have to call it from our router. You will see the implementation later on.
import { useRoutes } from 'react-router';
import routesConfig from './routes-config';
const RouteRenderer = () => {
const routes = useRoutes(routesConfig);
return routes;
};
export default RouteRenderer;
You may have seen that we have included useRoutes
, a hook from react-router, in this particular file. This feature was added in the react-router version 6 release. So, if you are planning to use this hook, you will have to use react-router v6 or above.
The hook (useRoutes) is converting our list of objects into router components that will be called in the following section.
Routes in App.js(x)
In our App.js or App.jsx file, we will have to add a router. To do that use the following code:
import { BrowserRouter as Router } from 'react-router-dom';
import RouteRenderer from './core/routes/route-renderer';
import './App.css';
function App() {
return (
<Router>
<RouteRenderer />
</Router>
);
}
export default App;
We have imported BrowserRouter as Router from react-router-dom and from now, our router should handle the provided (rendered) routes.
Conclusion
This method allows us to easily create a lot of routes, without touching and expanding <Route> elements inside the Router.
More details you can find in the attached video.
If you would like to download a repo with the complete code and setup, you can do it by visiting this Github link.