I'm newbie with react but i saw something weird. I've got all of my routes something like below:
<Main>
<Route exact path="/home" component={Home} />
<Route exact path="/home1" component={Home1} />
<Route exact path="/home2" component={Home2} />
<Route exact path="/home3" component={Home3} />
<Route exact path="/home4" component={Home4} />
<Route exact path="/home5" component={Home5} />
<Redirect from="*" to="/home" />
</Main>
is there any way to use an array and map instaed of paste another one <Route /> component?
I think about somehting like this:
routes.ts
const routes = [
{ path: "/home", component: SomeComponent },
{ path: "/home2", component: SomeComponent2 },
];
indes.tsx
<Main>
{ routes.map(route => (
<Route exact path={route.path} component={route.component} />
))}
</Main>
but i don't know how to pass new component into object in routes list.
Thanks for any help!
Note: Which react-router-dom version are u using? This is a code example for RRD6
const routes = [
{ name: "/route1", component: <ClickLabel /> },
{ name: "/route2", component: <Focus /> },
{ name: "/route3", component: <Counter /> }
];
/*--------------***/
{routes.map(({ name, component }, i) => (
<Route key={i} path={name} element={component} />
))}
Here is example: https://codesandbox.io/s/happy-swartz-ikqdn?file=/src/App.js
If u are using RRDv5, then here is the code
{/* Want to pass some dynamic props */}
{routes.map(({ name, component }, i) => (
<Route
key={i}
path={name}
render={() => {
return React.createElement(
component,
{ p: "THis is the prop" },
null
);
}}
/>
))}
{/* Simply render a component */}
{routes.map(({ name, component }, i) => (
<Route key={i} path={name} component={component} />
))}