Nastro
Nastro

Reputation: 1769

Why React router v4 makes incorrect redirect?

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.

Upvotes: 0

Views: 51

Answers (1)

Bhojendra Rauniyar
Bhojendra Rauniyar

Reputation: 85545

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} />

Upvotes: 1

Related Questions