0

Hello guys I got the following code inside my App.js file:

const history = createHistory();

function App({ calendarStore }) {
const [isLoggedIn, setIsLoggedIn] = useState(
    !!localStorage.getItem("isLoggedIn")
  );

  
  return (
    <div>
      
      <Router history={history}>
        <Navbar bg="primary" expand="lg" variant="dark">
          <Navbar.Brand href="/">Home</Navbar.Brand>
          <Navbar.Toggle aria-controls="basic-navbar-nav" />
          <Navbar.Collapse id="basic-navbar-nav">
          <Navbar.Brand href="/">About Us</Navbar.Brand>
          <Navbar.Brand href="/register">Register</Navbar.Brand>
          <Navbar.Brand href="/login">Login</Navbar.Brand>
          </Navbar.Collapse>
        </Navbar>
        <Route
          path="/"
          exact
          component={props => (
            <HomePage {...props} calendarStore={calendarStore} />
          )}
         />
          <Route 
          path='/login'
          exact
           component={login} 
           
          />
          <Route 
          path='/register'
          exact
           component={register} 
           />
      </Router>
    </div>
  );
}
  


export default App;

I was wandering How i can attach LoggedIn value inside my Code so if user is notLoggedIn he can see only Register and Login page and when he logs he will only can see the homepage from the Navbar.

3 Answers3

1

Both above answers are correct in that you can use conditional rendering to ensure that the page does not render the component dependent upon if the user is logged in or not.

However, this does not stop people from accessing the route by entering it into the browser.

You should check out private-routes from React-Router-Dom V6, this will ensure that even if by accident, the link to the register page, cannot be accessed by those who have already registered.

Just an added extra to ensure that people cannot create multiple accounts etc.

How to use Private route in react-router-dom@v6

Edit: You can use useEffect to detect the object (if it is saved in LS) and then set the state too true if it does exist.

useEffect(() => {
if(localStorage.getItem("isLoggedIn")){
  setIsLoggedIn(true)
 } else {
   setIsLoggedIn(false)
  }
})

This will check if the localStorage.getItem("isLoggedIn") exists and then set the loggedIn state to true if found, else, it will keep it false.

I would set the initial state of

const [isLoggedIn, setIsLoggedIn]=useState(false)
Venex
  • 101
  • 7
  • i used the above answers but my Navbar didnt change at all when i loggedIn with my credentials and with Token – takis Paras Nov 24 '22 at 14:46
  • Does it work if you don't log-in? – Venex Nov 24 '22 at 15:03
  • no even if i login or not the navbars remain the same no idea why – takis Paras Nov 24 '22 at 15:06
  • If you console.log(isLoggedIn) what does it return? – Venex Nov 24 '22 at 15:12
  • it returns null basically the problem is that i take user Token when he is loggedIn so i need to check the state of token each time the user logs in . U have any idea how to do it? Im coming from Vue and there was a store to do this job – takis Paras Nov 24 '22 at 15:20
  • Why not, check to see if the user token exists and if it does, then simply set the state as the boolean true. This can be achieved with the useEffect hook, that will run as soon as the component is called. – Venex Nov 24 '22 at 15:22
  • can u make me an example plz? im new to react and have no idea – takis Paras Nov 24 '22 at 15:25
  • i saw the answer i guess its correct but i want to search the token and not the state isLoggedIn so when i click logout it will dismiss the token – takis Paras Nov 24 '22 at 16:17
0

Take a look at conditional rendering https://reactjs.org/docs/conditional-rendering.html

{isLoggedIn && <Navbar.Brand href="/">Home</Navbar.Brand>} // show only if logged in
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Navbar.Brand href="/">About Us</Navbar.Brand>
{!isLoggedIn && <Navbar.Brand href="/register">Register</Navbar.Brand>} // show only if not logged in
{!isLoggedIn && <Navbar.Brand href="/login">Login</Navbar.Brand>}
0

You could always use the useState feature in react, for example:

const [loggedIn, setLoggedIn] = useState(false)

and then inside the return of the component

{loggedIn ? <NavbarLoggedIn /> : <Navbar />}

You could also use Redux toolkit for global states, that would be a better solution to be fair, but yeah thats a basic way of implementing this

  • i added it to my code but it didnt work it still shows me register/login on my navbars when user is loggedIn – takis Paras Nov 24 '22 at 15:08
  • So basically, this code depends on the logged in nav and normal nav being 2 different components, but like it should give you an idea on how to choose if you want to render different components depends on the state... – Ahmad Nasser Nov 24 '22 at 15:34