Reputation: 39
I have a separate routes.js:
export const routes = [
{pathname: "/", exact: true, name: "Home Page", id: "home", component: Home},
{pathname: "/about", exact: true, name: "About Us", id: "about", component: About},
{pathname: "/services", exact: true, name: "Services", id: "services", component: Services},
{pathname: "/portfolio", exact: true, name: "Portfolio", id: "portfolio", component: Portfolio},
{pathname: "/careers", exact: true, name: "Careers", id: "careers", component: Careers},
{pathname: "/partners", exact: true, name: "Partners", id: "partners", component: Partners},
{pathname: "/contact", exact: true, name: "Contact Us", id: "contact", component: Contact},
{pathname: "/blog", exact: true, name: "Blog", id: "blog", component: Blog},
{pathname: "/not-found", exact: true, name: "Not Found", id: "not-found", component: NotFound},
];
It's imported to my App.js like this:
import { routes } from './routes.js';
const App = (props) => {
return (
<div className='app-wrapper'>
<Header />
<BgVideo />
<Switch>
<Route path={routes[0].pathname} exact component={routes[0].component} />
<Route path={routes[1].pathname} exact component={routes[1].component} />
<Route path={routes[2].pathname} exact component={routes[2].component} />
<Route path={routes[3].pathname} exact component={routes[3].component} />
<Route path={routes[4].pathname} exact component={routes[4].component} />
<Route path={routes[5].pathname} exact component={routes[5].component} />
<Route path={routes[6].pathname} exact component={routes[6].component} />
<Route path={routes[7].pathname} exact component={routes[7].component} />
<Route path={routes[8].pathname} exact component={routes[8].component} />
<Redirect to='/not-found' />
</Switch>
</div>
);
};
Right now this works as expected, but I'd like loop over routes array and not to repeat <Route/>
9 times.
Upvotes: 0
Views: 1294
Reputation: 2129
<Switch>
{routes.map(route =>
<Route key={route.id} path={route.pathname} exact component={route.component} />
)}
<Redirect to='/not-found' />
</Switch>
This is basic React stuff and you should go through an introductory tutorial is my recommendation.
Upvotes: 2