Routing organizational principles and best practices in React applications
P粉046387133
P粉046387133 2023-08-16 16:15:12
0
1
491
<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粉046387133
P粉046387133

reply all(1)
P粉164942791

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!