4

I have a log out button that I only want to show when the user is logged in.

I have created a function for this purpose and included the function in the return part of react but it's not working.

This is the function:

const ifloggedin = () => {
    if (!localStorage.hasOwnProperty('token')) {
      return null
} else {
return <li><a href="#contact" className="Contact" onClick={logout} to={"/"}>Log Out</a></li>
}
  }

This is how I am trying to render it in return:

        <div className="content">
          <li><a href="#hiw" className="Hiw" to={"/about"}>HOW IT WORKS</a></li>
          <li><a href="#pricing" className="Price" to={"/pricing"}>PRICING</a></li>
          <li><Link className="Faq" to={"/Faq"}>FAQ</Link></li>
          <li><a href="#contact" className="Contact" to={"/contact"}>CONTACT</a></li>
          {ifloggedin}
        </div>

2 Answers 2

9

ifloggedin is a function so you need to call it.

 <div className="content">
          <li><a href="#hiw" className="Hiw" to={"/about"}>HOW IT WORKS</a></li>
          <li><a href="#pricing" className="Price" to={"/pricing"}>PRICING</a></li>
          <li><Link className="Faq" to={"/Faq"}>FAQ</Link></li>
          <li><a href="#contact" className="Contact" to={"/contact"}>CONTACT</a></li>
          {ifloggedin()}
</div>
Sign up to request clarification or add additional context in comments.

Comments

2

You have to call ifloggedin as ifloggedin(), because it is an arrow function. But in your case you are using it for conditional rendering so no need to write arrow function for that.

You can write it as normal function and use as ifloggedin()

 ifloggedin() {
if (!localStorage.hasOwnProperty('token')) {
  return null;
} else {
  return (
    <li>
      <a href="#contact" className="Contact" onClick={logout} to={'/'}>
        Log Out
      </a>
    </li>
  );
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.