React route returns nothing?

Viewed 139

I want to add a conditional route in my component, so if a user is logged in I return the component, and if not I want to navigate to the login page.

When I do that nothing is displayed on my page. How to manage it correctly?

import { Route } from 'react-router-dom';
import { UserContext } from '../UserContext';
import Login from './Login';
import React, { useContext } from 'react'

function ShoppingList() {
const  { user }  = useContext(UserContext);
if (user) {
return (
..... //content
);
}
else {
    return (
      <div>
        <Route path='/login' component={Login} />
      </div>
      );
  }
}
export default ShoppingList;

I tried also Navigate but I got an error and the same thing with the history.

2 Answers
// forward
if (!user) return <Login />
return (
  <Switch>
    <Route path="/some-path" component={SomeComponent} />
    ....
  </Switch>
)
// redirect
const AuthRoute = (props)=> {
   const user = useContext(UserContext);
   if (!user) return <Redirect to="/login" />
   return <Route {...props} />
}
const Main = ()=> {
 return (
  <Switch>
    <AuthRoute path="/some-path" component={SomeComponent} />
    <Route path="/login" component={Component} />
  </Switch>
 )
}

you can define your Route simply without any problem but adding a custom hook or any other implementation of an authentication checker will help you.

for example, you can check your user's auth and other information in the above function and send him to the login page.

// rest of the codes ...
import {useHistory} from 'react-router-dom'

function ShoppingList() {
   // rest of the codes ...

   const history = useHistory();

   if(user.status !== 'loggedIn'){ // ---> example login checker
        history.push('/loign')
   }

    return (
      <div>
        <Route path='/home' component={home}/>
        // other routes
        <Route path='/login' component={Login} />
      </div>
      );
       

Related