0

I have a simple React app and I'm trying to implement auth logic. This is how my application looks like:

class App extends Component {
    render() {
        return (
            <Router history={history}>
                <div className="App">
                    <Switch>
                        <PrivateRoute path="/account" component={Account} />
                        <Route component={PublicLayout} />
                    </Switch>
                </div>
            </Router>
        )
    }
}

My auth logic is: if user isAuthenticated === true render /account page else redirect to /signin. So for this I created my own simple PrivateRoute functional component:

export default ({ component: Component, ...args }) => {
    return (
        <div>
            <Route {...args} render={(props) => {
                return fakeAuth.isAuthenticated === true
                    ? <Component {...props} />
                    : <Redirect to='/signin' />
            }} />
        </div>
    )
}

Because PrivateRoute path="/account" is NOT exact path I expect that if user goes to /account-setting it will redirect him to /sign-in. But it's not working. The user successfully goes to /account-setting and see PublicLayout.

Why is that? There is no exact key in route, it has to grab all that starts from "/account" and use my logic in the PrivateRoute functional component.

Wexoni
  • 4,845
  • 6
  • 50
  • 89
Nastro
  • 1,330
  • 1
  • 15
  • 32
  • 1
    Why do you need to redirect? Just render the `/signin` component. Besides that, now you are using a fakeAuth but you might consider using a main `Auth` and redirect from there since the auth process might be async – Cristian S. Oct 30 '18 at 10:05

1 Answers1

1

Not providing exact props doesn't mean that it will match /account, /account-settings but it will match /account, /account/other, /account/other/paths. So, you'll need to provide both path:

<PrivateRoute path="/account" component={Account} />
<PrivateRoute path="/account-setting" component={Account} />

Or, you may use regex:

<PrivateRoute path="/account(?=\S*)([a-zA-Z-]+)" component={Account} />
Bhojendra Rauniyar
  • 73,156
  • 29
  • 131
  • 187