gothinkster / react-redux-realworld-example-app

Exemplary real world application built with React + Redux
https://react-redux.realworld.io
MIT License
5.55k stars 2.5k forks source link

Auth redirection not working #109

Open dhaval-cygnet opened 6 years ago

dhaval-cygnet commented 6 years ago

When I open the article editor page when I am not logged in then app not redirecting to login page.

khanof89 commented 4 years ago

create private route file as follows:

import React from 'react'; import {Route, Redirect} from 'react-router-dom';

const PrivateRoute = ({ component: Comp, loggedIn, path, ...rest }) => {
  return (
    <Route
      {...rest}
      render={props => {
        return loggedIn ? (
          <Comp {...props} />
        ) : (
          <Redirect
            to={{
              pathname: "/",
              state: {
                prevLocation: path,
                error: "You need to login first!",
              },
            }}
          />
        );
      }}
    />
  );
};

export default PrivateRoute;

and then in your App.js use it like follows

<PrivateRoute path="/protected-page" loggedIn={this.props.currentUser ? true : false} component={ProtectedComponent} />