'NotFound Component in React renders in every page
Upon wrong URL request I am redirecting it to PageNotFound Component. Below is the code.
let routes = (
<Switch>
<React.Fragment>
<Route path='/learning' exact component={Learning} />
<Route path='/login' component={Login} />
<Route path='/home' component={Login} />
<Route path='/about' component={Login} />
<Route path='/profile' component={Login} />
<Route path='/' exact component={Login} />
<Route component={PageNotFound} />
</React.Fragment>
</Switch>
);
<BrowserRouter>
<Suspense fallback={<PuffLoader color={'#000000'} size={150} css={override} loading={true} />}>
<ThemeProvider theme={theme}>
<CssBaseline />
{routes}
</ThemeProvider>
</Suspense>
</BrowserRouter>
But when I redirect to login page two components are rendering. one component-> (Login Component) second component-> (PageNotFound Component)
Any idea how to render only one component when landing upon login page and any wrong URL request I want to redirect it to PageNotFound Component. Currently I am using below versions-->
"react-redux": "^7.2.1",
"react-router": "5.1.2",
"react-router-dom": "5.1.2",
"react": "^16.13.1",
"react-dom": "^16.13.1"
Solution 1:[1]
According to the docs v5.reactrouter
How is this different than just using a bunch of
<Route>s?
<Switch>is unique in that it renders a route exclusively. In contrast, every<Route>that matches the location renders inclusively.
So remove the fragment surrounds your <Route> it would work
import { Route, Switch } from "react-router";
let routes = (
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route path="/login">
<Login />
</Route>
<Route>
<PageNotFound />
</Route>
</Switch>
);
Solution 2:[2]
I have fixed this issue by removing <React.Fragment> and also by adding some extra code to redirect.
let routes = (
<Switch>
<Route path='/learning' component={Learning} />
<Route path='/login' component={Login} />
<Route path='/home' component={Login} />
<Route path='/about' component={Login} />
<Route path='/profile' component={Login} />
<Redirect from='/' to='/login' exact />
<Route path='*' component={PageNotFound} />
</Switch>
);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | nos nart |
| Solution 2 | rishi raj |
