My application routes are an array that is mapped inside <Router>
which seems to be a common approach. I want to pass some extra props to the <Component />
. When I explicitly name the prop, it is passed to <Component />
and I can use it, however, when I spread the props, it is undefined in the <Component />
.
I need to spread the props because I want to pass through other props in the future and don't want to explicitly name all the props in App.js.
How can I ensure <Component />
receives props from ``routes``` without naming the props explicitly?
My code:
When I spread the props, they won't pass to the child component:
const routes = [
{
type: PublicRoute,
path: "/login",
component: LoginForm,
register: true, // I want to pass this prop
}
]
<Router history={history}>
<Switch>
{routes.map((route, i) => {
const RouteType = route.type;
const Component = route.component;
const Dashboard = dashboard;
return (
<Route
key={i}
path={route.path}
exact
render={(props) => (
<RouteType role={route.role}>
<Dashboard>
<Component {...props} /> // register not passed
</Dashboard>
</RouteType>
)}
/>
);
})}
</Switch>
</Router>
If I name the prop (register), it passes to the child component fine:
const routes = [
{
type: PublicRoute,
path: "/login",
component: LoginForm,
register: true, // I want to pass this prop
}
]
<Router history={history}>
<Switch>
{routes.map((route, i) => {
const RouteType = route.type || Fragment;
const Component = route.component;
const Dashboard = dashboard;
return (
<Route
key={i}
path={route.path}
exact
render={(props) => (
<RouteType role={route.role}>
<Dashboard>
<Component register={route.register} /> // register is passed ok
</Dashboard>
</RouteType>
)}
/>
);
})}
</Switch>
</Router>
Thanks.
You can pass like this.
<Component {...route, ...props} />