Home > Blockchain >  How can i shorten my React Route with map?
How can i shorten my React Route with map?

Time:11-14

What I have

import Home from "./components/underpages/Home";
import Kontakt from "./components/underpages/Kontakt";
import FAQ from "./components/underpages/FAQ";

// [...]


<Routes>
        <Route path="/"           element={<Home      />} />
        <Route path="/Kontakt"    element={<Kontakt   />} />
        <Route path="/FAQ"        element={<FAQ       />} />
      </Routes>

What I want:

{siteList.map((sites) => (
              import {site.Name} from "./components/underpages"   {site.path};
            ))}

// [...]

 {siteList.map((sites) => (
              <Route
              path=   {site.path}
              element={<{site.emelent}  />}
              />
            ))}

is there a way something like this, which will work?

I want to shorten my Routes and use the .map-function. in this way, it doesn't work, but is there another way?

CodePudding user response:

you can simply make array

like this :

const routes = [
  {
    path:'/',
    element:Home,
  },
  {
    path:'/Kontakt',
    element:Kontakt,
  },
  {
    path:'/FAQ',
    element:FAQ,
  }
]

and use it in this way :

      <Routes>
        {
          routes.map(({path,element:Component})=>{
            <Route path={path}           element={<Component/>} />
          })
        }
      </Routes>

CodePudding user response:

While you could load all the route up into an array and map over them:

import Home from "./components/underpages/Home";
import Kontakt from "./components/underpages/Kontakt";
import FAQ from "./components/underpages/FAQ";

const routes = [
  {
    path: "/",
    Component: Home,
  },
  {
    path: "/Kontakt",
    Component: Kontakt,
  },
  {
    path: "/FAQ",
    Component: FAQ,
  },
];

...

<Routes>
  {routes.map(({ path, Component }) => (
    <Route key={path} path={path} element={<Component />} />
  ))}
</Routes>

A simpler approach is to use a more optimal routes configuration and the useRoutes hook provided by react-router-dom.

Example:

import { useRoutes } from 'react-router-dom';
import Home from "./components/underpages/Home";
import Kontakt from "./components/underpages/Kontakt";
import FAQ from "./components/underpages/FAQ";

const routes = [
  {
    path: "/",
    element: <Home />,
  },
  {
    path: "/Kontakt",
    element: <Kontakt />,
  },
  {
    path: "/FAQ",
    element: <FAQ />,
  },
];

...

const routeElements = useRoutes(routes);

...

return routeElements;
  • Related