Accepted answer

I would recommend Lifting State Up in this case:

function App() {
  const [loggedIn, setLoggedIn] = useState(
    // initial value
    document.cookie.split(';').some((item) => item.trim().startsWith('logedIn=')));

  return (
    <div className="App">
      <Navbar {...{loggedIn}} />
        <Route exact path='/about' component={About} />
        <Route exact path='/signup' component={SignUp} />
        <Route exact path='/login' render={
          (routeProps) => <LogIn {...{setLoggedIn, ...routeProps}} />
        } />
        <Route exact path='/account' component={UserAccount}/>
        <Route exact path='/' component={Home} />
      <Footer />

and use the additional props in Navbar and LogIn components (cookies only used when reloading the page for the initial state above, not inside Navbar):

fucntion Navbar(props) {
  return (
      {props.loggedIn ? ... // instead of this.state.loggedIn


  1. You shouldn't duplicate a lot of code a believe you can change the links in a better way like this: render() { const link1 = this.state.loggedIn ? '/myaccount' : '/login'; const link1 = this.state.loggedIn ? '/logout' : '/signup'; return ( ... <ul className="navbar-nav"> <NavLink className="nav-link mr-3" to={link1}>My account</NavLink> <NavLink className='nav-link' to={link2}>Log out</NavLink> </ul> ) }
  2. Not fully understand why you check if user logged in through cookies, maybe there is better option as JWT autorization ? here is a link


Checking whether a user is logged in is probably out of the scope of this question, but you seem to be handling it anyway.

As you cannot use if statements in JSX, the two accepted ways to conditionally render JSX based on certain values is either via a ternary operator or a switch statement if you have multiple conditions to check against.

An example of using a ternary operator would be when you need to render a different navbar based on whether a user is logged in or not.

An example of when you would use a switch statement would be when you had multiple user roles and each of them needed to see a different iteration of a navbar.

Related Query

More Query from same tag