How can I make conditional rendering properly in React.js?

Viewed 92

recently, I am making my web application with a react and I'm struggling with a small issue(not small for me)

Below is my app.js and I want to conditional render NAV component by login/out status. (as you can see it is outside Switch!)

<>

      <Nav indexStatus={indexStatus} setIndexStatus={setIndexStatus} />
      
      <Index indexStatus={indexStatus} setIndexStatus={setIndexStatus} />

      <Switch>
        <Route exact path="/" component={Auth(LandingPage,null)}/>
        <Route exact path="/login" component={Auth(LoginPage,false)}/>
        <Route exact path="/calendar" component={Auth(Calendar,true)} />
        <Route exact path="/about" component={Auth(About,false)} />
        <Route exact path="/register" component={Auth(RegisterPage,false)}/>
      </Switch>
      
    </>

to check login status I gave true/false value to localStorage when user login/out

login:

dispatch(loginUser(body))
    .then(response=>{
      if(response.payload.loginSuccess){
        localStorage.setItem('user',response.payload.loginSuccess)
        props.history.push("/")
       console.log(props.parentNode)
       
       
      }else{
        alert('login failed')
      }
    })

logout:

 axios.get("/api/users/logout")
    .then(res=>{
      if(res.data.success){
        console.log(res)
       history.push('/login')
       localStorage.setItem('user','false')

        
    }else{
        alert("Logout failed")

    }
  })
}

and I gave localStorage value to state like below:

const [loginStatus,setLoginStatus] =useState(localStorage.getItem('user'))

I check it with console.log and it works fine

so I used ?: operator to do conditional render my component

loginStatus==false ? 
  <div>
  <div className="nav">
    <h2>TITLE</h2>
    <div className="buttons">
      <div>About</div>
      <div>How to use</div>
      <button onClick={logoutHandler}>Logout</button>

    <StyledLink to="/login"><FontAwesomeIcon icon={faSignInAlt}/></StyledLink>
    
    
      <button onClick={()=>setIndexStatus(!indexStatus)} >Index</button>
    </div>
  </div>
</div>


:
  <div>
  <div className="nav">
    <h2>TITLE</h2>
    <div className="buttons">
      <div>About</div>
      <div>How to use</div>
      <button onClick={logoutHandler}>Logout</button>

    <StyledLink to="/login"><FontAwesomeIcon icon={faSignInAlt}/></StyledLink>
    <StyledLink to="/register"><FontAwesomeIcon icon={faUserPlus}/></StyledLink>
    
      <button onClick={()=>setIndexStatus(!indexStatus)} >Index</button>
    </div>
  </div>
</div>
 

However, It doesn't work at all even tho I changed option like loginstatus ===true or loginstatus ? etc.

Can you tell me what's wrong with my logic or coding? thx for reading this your help will be appreciated.

0 Answers
Related