Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I split React Router into multiple files

My routes file is getting rather messy so I decided to split them out into separate files.

My problem is that if I used 2 separate files, whichever comes after the first include does not get rendered:

const routes = (
  <div>
    <Switch>
      <Route exact path="/" component={Home} />
      {Registration} //Does get rendered

      //Everything below this does not get a route
      {Faq}
      <Route path="/login" component={login} />
      <Route component={NoMatch} />
    </Switch>
  </div>
);

If I switch Faq with registration then all the Faq routes will work.

RegistrationRoutes.js

import Introduction from '../containers/Registration/Introduction';
import Login from '../containers/Login';

const Routes = (
  <Switch>
    <Route path="/login" component={Login} key="login" />,
    <Route path="/registration/introduction" component={Introduction} key="registration-intro" />
  </Switch>
);
export default Routes;

FaqRoutes.js

import Faq from '../containers/Faq';
import faqJson from '../json_content/faq/faq';
import FaqCategory from '../containers/Faq/faqCategory';

const Routes = (
  <Switch>
    <Route path="/faq/:category" component={FaqCategory} key="faqCat" />
    <Route path="/faq" render={props => <Faq data={faqJson} />} key="faq" />
  </Switch>
);
export default Routes;
like image 546
Jamie Hutber Avatar asked Sep 19 '18 17:09

Jamie Hutber


People also ask

Does React Router code split?

The react-router-dom library supports inbuilt route-level code splitting. It allows us to download chunks at the route level. Using this feature, we'll code split at the route level, which is tremendously helpful.

Can we have multiple routes in React JS?

EDITED: Multiple routed with multiple layouts can be done by using <Outlet> component in layouts and <Route> component composition.

What is Route and Route splitting?

Route-based code-splitting is a method of splitting React components that involves using dynamic import() on lazy load route components. react-loadable is a higher-order component (HOC) that uses the dynamic import() syntax to load React components with promises.


1 Answers

May be you can move them to config file and load them from there.

App.tsx

import routes from "./routes";
const App: React.FC = () => {
  return (
      <BrowserRouter>
        <div>
          <Switch>
            {routes.data.map((entry) => {return (<Route {...entry}/>)})}
          </Switch>
        </div>
      </BrowserRouter>
  );
};

export default App;

router.ts

const routes = {data: [
        {
            key: "one",
            path: "/three"

        },
        {
            key: "two",
            path: "/two"
        }
    ]
}

export default routes;

This will keep your code simple

like image 77
Codex Avatar answered Sep 25 '22 02:09

Codex