I am trying to build some routes using react router v5 and basically I have a layout(Dashboard and this dashboard has some routes.) so if I do '/dashboard' it doesn't work'. the '/dashboard' comes from the routes that I map at the last piece of code, which is basically inside the AppContent which is the layout not sure what I am missing here...
my App.js file
<Router>
<Switch>
<Route
exact
path="/"
name="Home"
render={(props) => <DefaultLayout {...props} />}
/>
<Route
path="/login"
name="Login Page"
render={(props) => <Login {...props} />}
/>
<Route
path="/register"
name="Register Page"
render={(props) => <Register {...props} />}
/>
<Route
path="*"
name="Page 404"
render={(props) => <Page404 {...props} />}
/>
</Switch>
</Router>
my DefaultLayout File:
<div>
<AppSidebar />
<div className="wrapper d-flex flex-column min-vh-100 bg-light">
<AppHeader />
<div className="body flex-grow-1 px-3">
<AppContent />
</div>
{/* <AppFooter /> */}
</div>
</div>
my AppContentFile:
<Router>
<Switch>
{routes.map(
(route) =>
route.component && (
<Route
key={route.name}
path={route.path}
exact={route.exact}
name={route.name}
render={(props) => (
<route.component {...props} />
)}
/>
)
)}
<Redirect to="/" />
</Switch>
</Router>
The exact prop on the home "/" path necessarily precludes it from matching any nested route paths. In other words, when the path is "/dashboard" it now no longer exactly matches "/" and the layout component rendering the content is unmounted, unmounting any potential routes. It should be removed.
You also only need a single router component to provide a routing context for the entire app, so remove the extraneous Router in AppContent.
Recall also the within a Switch component that path order and specificity matters, so order your paths from more specific to less specific.
App
<Router>
<Switch>
<Route path="/login" name="Login Page" component={Login} />
<Route path="/register" name="Register Page" component={Register} />
<Route
path="/" // <-- can now match sub-routes
name="Home"
component={DefaultLayout}
/>
<Route name="Page 404" component={Page404} />
</Switch>
</Router>
AppContent - remove the Router
<Switch>
{routes.map((route) =>
route.component && (
<Route
key={route.name}
path={route.path}
exact={route.exact}
name={route.name}
render={(props) => (
<route.component {...props} />
)}
/>
)
)}
<Redirect to="/" />
</Switch>
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