3
votes

I have this private route component that is used to render a component only is the user is logged in, else it should redirect to the login page.

const PrivateRoute = ({ component: Component, ...rest }) => (
    <Route {...rest} render={props => (
            authToken()
            ? <Component {...props} />
            : <Redirect to={{ pathname: '/login', state: { from: props.location } }} />
    )} />
)

export default withRouter(PrivateRoute);

and this is my main app:

            <BrowserRouter>
                <div className="wrapper">
                    <Switch>
                        <Route path="/login" component={LoginPage} />
                        <> 
                        <div className="dashboard">
                            <SideBar />
                            {permittedEvents &&
                                <div className="content-area">
                                    <PrivateRoute exact path="/" component={Dashboard} />
                                    <PrivateRoute exact path="/calendar" component={Calendar} />
                                </div>
                            }
                        </div>
                        </>
                    </Switch>
                </div>
            </BrowserRouter>

for some reason the redirect is being ignored completely and when the user is not logged in, the Sidebar gets rendered but nor the content or the login page get rendered.

I have tried returning only the redirect in te Private route to force te redirect and check whether it was something wit my authentication. But the redirect doesn't seem to be working no matter where its included.

1

1 Answers

3
votes

You don't need Route

class PrivateRoute extends React.Component {
    constructor(props) {
        super(props);
    }

    render() {
        const { component: Component, ...rest } = this.props;

        const redirectPath = (<Redirect to={{
            pathname: "/login",
            state: {
                from: this.props.location.pathname
            }
        }}/>);

   if (!ok) {
                return redirectPath;
            }
        return <Component {...this.props} />;
    }
};

export default  withRouter(PrivateRoute);