How to remove Login button from nav bar after logging in

Viewed 1859

I am building a website that has 3 different pages (Home, Login, and User), and I am using Switch Component in React Router to move between pages. The issue I have is when I get to the user page, I still see the login in the navigation list as shown in the image below enter image description here Now I want the Login button to be removed once I get to the user page or switch the text to "Logout". Do you have any suggestions on how this could be done. I also included the code so it's more clear

Header (Navbar) Component

import React from "react";
import { Link } from "react-router-dom";
import './App.css';

const Header = () => (
  <header >
    <nav className='topnav'>
      <ul>
          <li>
            <Link to="/Login">Login</Link>
          </li>
          <li>
            <Link to="/">Home</Link>
          </li>

      </ul>
    </nav>
  </header>
);

export default Header;

Login Component

const Login = () => (

  <Switch>
    <div className="LoginWrap">
      <Route exact path="/Login" component={LoginForm} />
      <Route path="/Login/:number" component={User} />
    </div>
  </Switch>

);

export default Login;

and the User component is here.


Edit: Based on your suggestions, I tried to do this:

<Link to="/Login">
{
  console.log("Header localStorage.getItem isLoggedIn is :" + localStorage.getItem("isLoggedIn"))
}
{
  localStorage.getItem("isLoggedIn") === true? "Logout" : "Login"
}
</Link>

However, it was showing "Login" all the time.

I have no idea why. Even though in the console it prints "Header localStorage.getItem isLoggedIn is :true" and "Header localStorage.getItem isLoggedIn is :false" correctly when you login through the login form and then press the Link button on the header


Even more strange was that when I changed the code to

localStorage.getItem("isLoggedIn") ? "Logout" : "Login"

, it always shows "Logout"

3 Answers

If you want to use Redux to solve your issues, can check out my simple redux sample in my github repository (https://github.com/saamerm/ReactAndRedux-CounterApp) that will be able to explain everything in details.

You just need to change up the index.js and the Counter.js (Login in your case) files for your application :

  1. Index.js
import React from "react";
import { render } from "react-dom";
import { BrowserRouter } from "react-router-dom";
import App from "./components/App";
import { Provider } from "react-redux";
import { createStore } from "redux";

const initialState = {
  isLoggedIn: false
};

function reducer(state = initialState, action) {
  switch (action.type) {
    case "LOGIN":
      return {
        isLoggedIn: true
      };
    case "LOGOUT":
      return {
        isLoggedIn: false
      };
    default:
      return state;
  }
}

const store = createStore(reducer);

render(
  <Provider store={store}>
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>,
  document.getElementById("root")
);

  1. Login component
import React from "react";
import { connect } from "react-redux";

class Login extends React.Component {
    login = () => {
        this.props.dispatch({ type: "LOGIN" });
    };
    logout = () => {
        this.props.dispatch({ type: "LOGOUT" });
    };

    handleLoginClick=()=>
    {
      if (this.props.isLoggedIn === true){  
        this.logout()
      }
      else{
        this.login()
      }
    }  
    
    render(){...}
}

function mapStateToProps(state) {
    return {
        isLoggedIn: state.isLoggedIn
    };
}

export default connect(mapStateToProps)(Login);

Basically the convention is to use an authentication context to manage the state or you can also put the authenticate method in the context too. I just googled the example quickly, and find one clean example here.

One of the best basic method is setting a localStorage value when the user logins, and deleting this value when the user logouts. Something like this:

const auth = localStorage.getItem("islogin");

if (islogin) { // if there is a value named as islogin...
  <Button>Logout</Button>
} else { 
  <Button>Login</Button>
}

Related