0

I created app that redirects user to login page, and if he logged in than he can access other routs of the site that are defined in Home component. The problem is I cannot now add NotFound route. Here is my code

    <BrowserRouter basename="/">
                <main>
                    <Switch>
                        <Route exact path="/login"
                            render={(props) => <Login {...props} setLoggedIn={() => this.setLoggedIn()}/>}/>
                        <Route  path="/" render={(props) => (
                            this.state.isAdminLogin ? (
                                <Home {...props} />
                            ) : (
                                <Redirect to="/login"/>
                            )
                        )}/>
                       <Route component={NotFound} />
                    </Switch>
                </main>
            </BrowserRouter>

When i open not existing route it still shows home page...

Anna
  • 2,911
  • 6
  • 29
  • 42
  • The problem is that you have a Switch component and a Route with path='/' before the not found route which will always match and either Redirect or render Home component. You need to refactor your code a bit to write PrivateRoute HOC + a NotFoundRoute functionality – Shubham Khatri Oct 15 '18 at 07:47
  • The group of guys who downvoted all my questions yesterday - you just prevent developers to find answers, so thats not only stupid but egoistic – Anna Oct 24 '18 at 10:39
  • I am not sure what caused the one person to downvote, since you question seems valid and has a proper code for others to help you – Shubham Khatri Oct 24 '18 at 10:54

2 Answers2

1

You need a pattern in order for the route to be matched.

<Route path="*" component={NotFound} />

For this to work, make sure not any routes before it are matched, like in your example.

Webber
  • 4,672
  • 4
  • 29
  • 38
1

The problem in your case is that you have a Switch component which renders a Route with path='/' before the NotFound route which will always match and either Redirect or render Home component, thus the control never reaches the NotFound Route.

You need to refactor your code a bit to write PrivateRoute HOC. Refer to this link to implement a PrivateRoute component and use it for all the Routes that you want to authenticate and then for a non matching Route render the 404 Route

Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400