How to create seperate component just for routes using react router?

Viewed 750

like the title says I need to create separate component where I will store routes for my project. This is what I have done in App.js component:

 <Router>
    <Switch>
      <Route path="/" exact />
      <Route path="/messages/messagelist" exact />
      <Route path="/messages/ceostats" exact />
      <Route path="/resourcem/categories" exact />
      <Route path="/resourcem/subcategories" exact />
      <Route path="/resourcem/resources" exact />
      <Route path="/surveys" exact />
      <Route path="/userm/users" exact />
      <Route path="/userm/usergroups" exact />
    </Switch>
  </Router>

What I need to do now, is to extract them for example in separate component let's call it Route.js. How do I do that?

2 Answers

I prefer to separate the RouterProvider in this way:

First, let create a RouterProvider.js:

import React from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';


function RouterProvider() {
  return (
    <Router>
      <Switch>
        // Routes 
      </Switch>
    </Router>
  )
}

export default RouterProvider;

Now, create a routes.js file:

import HomePage from 'pages/home';
import AboutUsPage from 'pages/aboutUs';

const routes = [
  {
    path: '/home',
    component: HomePage,
    exact: true
  },
  {
    path: '/aboutUs',
    component: AboutUsPage,
    exact: true
  },
 // and so on for other routes in your project
]

export default routes;

Back to the RouterProvder.js and import the routes object and use it:

import React from 'react';
import {BrowserRouter as Router, Switch, Route} from 'react-router-dom';

import routes from 'path/to/routes' // ---> import from routes.js file

function RouterProvider() {
  return (
    <Router>
      <Switch>
        {
          routes.map(route => 
            <Route path={route.path} component={route.component} exact={route.exact} />
          )
        } 
      </Switch>
    </Router>
  )
}

export default RouterProvider;

Finally, add the RouterProvider as the last layer in the App.js file:

import RouterProvider from 'path/to/providers/routerProvider'

function App() {
   return (
      <ReduxProvdier>
         <RouterProvider/>
      </ReduxProvider>
   )
}

Note: ReduxProvider is just an example of other providers in your application like Toast provider or Network provider.

Note: creating routes object in routes.js is not useful in all cases for example if you wanna use Suspense/Lazy it's not working as your expectation.

Related