I can't figure this out even when looking on SO answers. I have a layout that looks like this:
const Dashboard = (props) => (
<div className={styles.views}>
<Route
to="/dashboard/reports/create"
render={() => <ReportsForm {...props} />}
exact
/>
<Route
to="/dashboard/reports"
render={() => <Reports {...props} />}
exact
/>
</div>
);
const routes = [
{ path: '/', component: Home, exact: true },
{ path: '/dashboard', component: Dashboard },
{ path: '/about', component: About, exact: true },
{ path: undefined, component: Error404 },
];
const Routes = () => {
return (
<Switch>
{routes.map((config, i) => {
const key = `path-${config.path}`;
return <Route key={key} {...config} />;
})}
</Switch>
);
};
const App = compose(
withRouter,
connect(mapStateToProps),
)(() => {
return (
<Router history={history}>
<IntlProvider>
<Routes />
</IntlProvider>
</Router>
);
})
I have a dashboard component responsible for rendering multiple tabs, so going to /dashboard/reports/create should only render the ReportsForm component, and going to /dashboard/reports should only render the Reports component. Currently both are rendered in both cases.
What am I doing wrong?
EDIT
When I try to print out the match prop in the Dashboard it gives me this – maybe this will be helpful:
{
"path": "/dashboard",
"url": "/dashboard",
"isExact": false,
"params": {}
}
Apart from typo that you pointed out for declaring to instead of path
You can wrap Dashboard component Routes in a Switch
const Dashboard = (props) => (
<div className={styles.views}>
<Switch>
<Route
path="/dashboard/reports/create"
render={() => <ReportsForm {...props} />}
exact
/>
<Route
path="/dashboard/reports"
render={() => <Reports {...props} />}
exact
/>
</Switch>
</div>
);
If that dont work you can even wrap the entire thing in Route with initial path as follows:
const Dashboard = props => (
<div className={styles.views}>
<Route path="/dashboard/reports"> // <------------------
<Switch>
<Route path="/dashboard/reports/create" render={() => <ReportsForm {...props} />} exact />
<Route path="/dashboard/reports" render={() => <Reports {...props} />} exact />
</Switch>
</Route>
</div>
);
Here's the working example solution that I just created: https://stackblitz.com/edit/react-uih91e-router-nested?file=index.js
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With