How to change login button to logout button in React

Viewed 7934

Hi I'm building a single page app using react.js for the first time, I'm struggling really badly with syntax here. I simply want to change the login button to a logout button when the user has signed in. Where am I going wrong?

render() {
  const isLoggedIn = this.state.isLoggedIn;

  return (
    if (isLoggedIn) {
      <div className="authentication">
        <button>Logout</button>
      </div>
    } else {
      <a href='http://localhost:8888'>
        <button>Login</button>
      </a>
    }
  );
}
3 Answers

You should use the if statement before using the return:

render() {
  const { isLoggedIn } = this.state;

  if (isLoggedIn) {
    return (
      <div className="authentication">
        <button>Logout</button>
      </div>
    );
  }

  return (
    <a href='http://localhost:8888'>
      <button>Login</button>
    </a>
  );
}

The better way is using the ternary operator in the return block:

render() {
  const { isLoggedIn } = this.state;

  return (
    <div>
      {
        isLoggedIn 
          ? (
              <div className="authentication">
                <button>Logout</button>
              </div>
            )
          : ( 
              <a href='http://localhost:8888'>
                <button>Login</button>
              </a>
            )
      }
    </div>
  );
}

And the best way can be:

handleAuth = () => {
  const { isLoggedIn } = this.state;

  if(isLoggedIn) {
    // Do logout
  } else {
    // Do login
  }
}

render() {
  const { isLoggedIn } = this.state;

  return (
    <button onClick={handleAuth}>
      {isLoggedIn ? 'Logout' : 'Login'}
    </button>
  );
}

if is a statement and you can use statement after return you should use ternary operator.

Also you nesting button inside a. You should use href directly on button

render() {
     const isLoggedIn = this.state.isLoggedIn;

    return (
      isLoggedIn ? 
      <div className="authentication">
        <button >Logout </button>
      </div>
      : 
      <button href='http://localhost:8888'>Login </button>
     )
}

You can create some function components and use it like:

function LogoutBtn(props) {
  return <div className="authentication"><button >Logout </button></div>;
}

function LoginBtn(props) {
  return <a href='http://localhost:8888'><button>Login </button></a>;
}

function AuthBtn(props) {
  const isLoggedIn = props.isLoggedIn;
  if (isLoggedIn) {
    return <LogoutBtn />;
  }
  return <LoginBtn />;
}

and then inside render method use it like:

render() {
    const {isLoggedIn} = this.state;
    return <AuthBtn isLoggedIn={isLoggedIn} />;
}
Related