Home  >  Q&A  >  body text

Routing organizational principles and best practices in React applications

<p>I have written multiple routes in the App.js file. </p> <pre class="brush:php;toolbar:false;">function App() { return ( <MainLayout> <Routes> <Route path="/a" element={<A />} /> <Route path="/b" element={<B />} /> <Route path="/c" element={<C />} /> <Route path="/d" element={<D />} /> </Routes> <Route path="/" element={<Login />} /> </MainLayout> )}</pre> <p>Now how do I organize these routes correctly? Since there are about 50 routes and the App.js file contains all 50 routes, I don't think this is a suitable structure. </p>
P粉046387133P粉046387133452 days ago496

reply all(1)I'll reply

  • P粉164942791

    P粉1649427912023-08-17 00:20:26

    You can create a new component AppRouter.jsx:

    import {routes} from "@/routes.js";
    
        export default function AppRouter() {
          return (
            <Routes>
              {routes.map(route => <Route path={route.path} element={route.component} />)}
            <Routes/>
          )
        }

    Then create a file containing routes routes.js:

    import A from "@/components/A";
    import B from "@/components/B";
    import C from "@/components/C";
    import Login from "@/components/Login";
    
    export const routes = [
      {
        path: "/a",
        component: <A />
      },  
      {
        path: "/b",
        component: <B />
      },
      {
        path: "/c",
        component: <C />
      },
      {
       path: "/",
       component: <Login />
      },
    ]

    Then use it in your App component:

    function App() {
    
      return (
       <MainLayout>
         <AppRouter/>
      </MainLayout> )}

    If you need to create new routes in the future, go to routes.js and add them there.

    reply
    0
  • Cancelreply