3

Where do we add a 404 page if some one try to access Home or any other page via url for eg: http://localhost:3000/home without login. The Home, Profile, Aboutus pages are accessible only after successful login.

App.js

const App = () => {                     
  return (
   <UserProfileContext.Provider value={{ data, setData }}>
      <BrowserRouter>
        <>
     <Navigation />
      <Switch>
          <ProtectedRoute exact path="/" component={Home} />
          <ProtectedRoute path="/profile" component={Profile} />
          <ProtectedRoute path="/aboutus" component={Aboutus} />
          <Route path="/register" component={Register} />
          <Route path="/login" component={Login} />
      </Switch>
    </>
   </BrowserRouter>
  </UserProfileContext.Provider>
  );
};
ReactDOM.render(
  React.createElement(App, null),
  document.getElementById("root")
);

export default App;

Navigation.js

const Navigation = () => {
    const history = useHistory();
    const { data } = useContext(UserProfileContext); // added 16 jun based on stack

    const divStyle = {
        float:'left',
        color: '#64cad8', 
        padding: '0px 0px 0px 10px',
        font:'Lucida, sans-serif'
      };

    function logout() {
        localStorage.removeItem('loginEmail')
        localStorage.removeItem('Privilege')
        history.push('/login')
        window.location.reload(true);
      }

    return localStorage.getItem('loginEmail') &&
        <div className="App">
            <div className="wrapper">
                <nav className="siteNavigation_nav_links">
                <div className="clubLogo landing"style={divStyle}><b>Southside Soccer</b></div>
                    <NavLink className="mobile_register_link" to="/">Home</NavLink>
                    <NavLink className="mobile_register_link" to="/profile">Profile</NavLink>
                    <NavLink className="mobile_login_link" to="/login" onClick={logout}>Logout</NavLink>
                    <NavLink className="mobile_login_link" to='/aboutus'>About us</NavLink>
                <div className="profileImage nav menu">
                <span>{data.name}</span>|<img src={data.photo}></img>
                </div>
                </nav>
            </div>
        </div>
}

export default Navigation;
soccerway
  • 10,371
  • 19
  • 67
  • 132

3 Answers3

2

for 404 page or error page do this:

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

remember to use exact on the routes you want views to be accessible at

your protected route should redirect to your login page if not successfully authenticated

Red Baron
  • 7,181
  • 10
  • 39
  • 86
2

A 404 error is when a page is not found - I think what you are looking for is a 401 error (which is an unauthorised access error). Firstly I'll answer your question; to handle a 401 error in react-router you typically you use default routes:

In earlier react-router:

<Route path='*' component={NotFoundComponent} />

In newer react router (version 4 and 5) just place the route last:

<Route path="/404" component={GenericNotFound} />
<Redirect to="/404" />

However, this will not solve your issue. What you want do do is show an error page if the user is not logged in. NOT whenever a user accesses an url that doesn't exist.

So there's two ways to do what you want. The first way is with a server (this is how it's usually done in the industry). You have three pages (login-page.js, 401-error.js, main-app.js). First the server sends the login-page.js. Then when a user logs in, you send the main-app.js page. If a user is not logged in but tries to access an url on the main-app.js then you send the 401-error.js page.

I understand that this carries a lot of overhead though so instead you can do it a slightly easier but less secure way through a single page application - which is probably what you intend to do anyway.

First you need to maintain some state about whether or not the user is logged in globally throughout your app (probably with redux). Then in each of your components (Home, Profile etc.) you have to check if a user is logged in, if not then redirect to the 404 page.

You can use history to redirect to a page programatically: Programmatically navigate using react router

 
 class Foo extends Component {
    componentDidMount() {
      if (reduxStore.userIsLoggedIn === false) {
          this.props.history.push('/401')
      }
    }
    /** -- snip -- **/
 }
 
 /** -- snip -- **/
 <Route render={({ history }) => 
     <Foo history={history}/>
 }/>
Dylan Kerler
  • 2,007
  • 1
  • 8
  • 23
0

In start of each page, you mush check login (variables) status of every user! If he/she has not login, redirect him/her to appropriate page! For example a page which show a message that "you need to login first".

Majid Hajibaba
  • 3,105
  • 6
  • 23
  • 55