Reputation: 706
I am implementing No Match route, it weird that it's being rendered with every specified route and also for non specified ( it should ), so it's rendering all time.
Here is some code to look into: RouterNavigation component that generates <Route />
using a array passed and at end add one <Route />
for 404.
<Fragment>
{RouteConfig.map((route, i) => (
<Route
render={({ location }) =>
route.isProtected ? (
isAuthenticated ? (
route.component
) : (
<Redirect
to={{
pathname: "/login",
state: { from: location }
}}
/>
)
) : (
route.component
)
}
exact={route.path === "/" ? true : false}
path={route.path}
key={i}
/>
))}
<Route
key={RouteConfig.length}
path="*"
render={({ location }) => {
return (
<SuspenseContainer>
<PageNotFound from={location.pathname} />
</SuspenseContainer>
);
}}
/>
</Fragment>
Importing my RouterNavigation component in App.tsx code :
<Router>
<Switch>
<RouterNavigation />
</Switch>
</Router>
After rendering
RouterNavigation Component Code
Update: One thing noticed is, when we create route dynamically, 404 route renders all times, below is the url that contains same example from react-router-dom for 404 route with little refactor ( i.e. by taking Route part and creating a component that renders that, same as we did)
https://codesandbox.io/embed/react-router-no-match-404-8eiv9?fontsize=14&hidenavigation=1&theme=dark
Package json
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-redux": "^7.1.3",
"react-router-dom": "^5.1.2",
Upvotes: 0
Views: 1202
Reputation: 2438
Instead of Fragment
use Switch
<Switch>
//routes go here
<Route ... />
...
</Switch>
Here: https://codesandbox.io/s/react-router-no-match-404-bn9yg
Route
needs to be a direct child of Switch
and Switch
outside of RouterNavigation
is extraneous, so we can remove it:
<Router>
<RouterNavigation />
</Router>
edited in the codesanbox above.
Upvotes: 1
Reputation: 706
Instead of using
<Router>
<Switch>
<RouterNavigation />
</Switch>
</Router>
which should work, as <Fragment>
let you group a list of children without adding extra nodes to the DOM.
Using in same component work
<Switch>
{RouteConfig.map((route, i) => (
<Route
render={({ location }) =>
route.isProtected ? (
isAuthenticated ? (
route.component
) : (
<Redirect
to={{
pathname: "/login",
state: { from: location }
}}
/>
)
) : (
route.component
)
}
exact={route.path === "/" ? true : false}
path={route.path}
key={i}
/>
))}
<Route
key={RouteConfig.length}
path="*"
render={({ location }) => {
return (
<SuspenseContainer>
<PageNotFound from={location.pathname} />
</SuspenseContainer>
);
}}
/>
</Switch>
Upvotes: 0