Navbar authenication in ReactJs

I want to change the navbar when the user logs into the site. I created two navbars for the signup/login page I want to prevent the user from using the links on the actual website. However, once they have logged in the website with the right credentials then they can see the real links necessary to use in the website.

Firstly, welcome to the forums.

While we are primarily here to help people with their Free Code Camp progress, we are open to people on other paths, too. Some of what you are asking is pretty trivial in the Free Code Camp context, so you might find that if you’re not getting the instruction and material you need in your current studies, the FCC curriculum will really help you get started. At a modest guess I’d say investing a 4-5 hours working through the curriculum here will really pay off. You can find the curriculum at https://www.freecodecamp.org/learn.

With your current questions, we don’t have enough context to know what you already know or don’t know, so it is impossible to guide you without just telling you the answer (which we won’t do).

It is pretty typical on here for people to share a codepen / repl.it / jsfiddle example of what they have tried so that anyone helping has more of an idea of what help is actually helpful.

Please provide some example of what you’ve tried and I’m sure you’ll get more help.

Happy coding :slight_smile:

Use the auth state to conditionally render the navigations.

As we have no way of knowing how the auth is implemented that is about as generic an answer we can give.

How to find the auth when using local storage?

I don’t see what localStorage has to do with it? I also have no idea how your auth system is implemented.

Whatever auth implementation you have should give you something back to identify the user or some falsy value if they are not a user. Simply use that to conditionally render elements.

function App() {
  const [isAuthenticated, setIsAuthenticated] = useState(false);

  return (
    <div className="App">
      {isAuthenticated ? (
        <>
          <nav style={{ display: 'flex', gap: '1rem' }}>
            <a href="#">Home</a>
            <a href="#">Products</a>
            <a href="#">Contact</a>
          </nav>
          <button onClick={() => setIsAuthenticated(false)}>Sign out</button>
        </>
      ) : (
        <button onClick={() => setIsAuthenticated(true)}>Sign in</button>
      )}
    </div>
  );
}

Also, I tried that but basically, I want the user sees a different navbar then the navbar on the home page. How to accomplish this?

const Navbar = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(true);
  const [isLoggedOut, setIsLoggedOut] = useState(false);
  const auth = localStorage.getItem("bredding");
 return (
<div>
    {  auth ?
  
    <nav className="nav-ul navbar navbar-dark bg-zinc-800 fixed w-full top-0 z-10">
      <div className="container flex sm:flex-row flex-col gap-2 justify-between items-center">
        <h1 className="fs-3">
          <Link to='/' className="text-white ">
              <span className="hover:text-blue-600">Music Essentials</span>
          </Link>
        </h1>
        <div className="flex items-center gap-4">
          <ul className="flex items-center gap-5 text-white">
            <li>
              <a href="/home">Home</a>
            </li>
            <li>
              <div className="dropdown-menu">
                <Link to="/music">
                  Music
                </Link>
                <div className="menu-content">
                  <a className="links-hidden" href="/genre">
                    Pop
                  </a>
                  <a className="links-hidden" href="/Hiphop">
                    Hip Hop
                  </a>
                  <a className="links-hidden" href="/Rock">
                    Rock
                  </a>
                  <a className="links-hidden" href="/EDM">
                    EDM
                  </a>
                  <a className="links-hidden" href="/RandB">
                    R&B
                  </a>
                  <a className="links-hidden" href="/Jazz">
                    Jazz
                  </a>
                </div>
              </div>
            </li>
            <li>
              <Link to="/Store">
              Store
              </Link>
            </li>
            <li>
              <a href="/News">News</a>
            </li>
            <li>
              <a href="/Contact">Contact</a>
            </li>

          </ul>
          {/* <div></div> */}
        </div>
      </div>
    </nav>
   : 


    
    <nav className="nav-ul navbar navbar-dark bg-zinc-800 fixed w-full top-0 z-10">
      <div className="container flex sm:flex-row flex-col gap-2 justify-between items-center">
        <h1 className="fs-3">
          <Link to='/' className="text-white ">
              <span className="hover:text-blue-600">Music Essentials</span>
          </Link>
        </h1>
        <div className="flex items-center gap-4">
          <ul className="flex items-center gap-5 text-white">
            <li>
              <a href="/">Home</a>
            </li>
            <li>
              <div className="dropdown-menu">
                <Link >
                  Music
                </Link>
                <div className="menu-content">
                  <a className="links-hidden">
                    Pop
                  </a>
                  <a className="links-hidden" >
                    Hip Hop
                  </a>
                  <a className="links-hidden">
                    Rock
                  </a>
                  <a className="links-hidden" >
                    EDM
                  </a>
                  <a className="links-hidden">
                    R&B
                  </a>
                  <a className="links-hidden" >
                    Jazz
                  </a>
                </div>
              </div>
            </li>
            <li>
              <Link>
              Store
              </Link>
            </li>
            <li>
              <a>News</a>
            </li>
            <li>
              <a >Contact</a>
            </li>

          </ul>
          {/* <div></div> */}
        </div>
      </div>
    </nav>
  
  
  }

    
    </div>

  );

Create two separate nav components. One for the main nav and one for the authenticated nav.

I see:

  const [isLoggedIn, setIsLoggedIn] = useState(true);
  const [isLoggedOut, setIsLoggedOut] = useState(false);

but I am not sure the point in having two of them (the first). You are not even using them which seems odd. Using your exiting code, you could do something like what @lasjorg mentioned.

const Navbar = ({ auth }) => {
  const { isAuthenticated, setIsAuthenticated } = auth;

  const AuthNav = () => (
    <>
      <nav style={{ display: "flex", gap: "1rem" }}>
        <a href="#">Home</a>
        <a href="#">Products</a>
        <a href="#">Settings</a>
      </nav>
      <button onClick={() => setIsAuthenticated(false)}>Sign out</button>
    </>
  );

  const MainNav = () => (
    <>
      <nav style={{ display: "flex", gap: "1rem" }}>
        <a href="#">Home</a>
        <a href="#">Products</a>
        <a href="#">Contact</a>
      </nav>
      <button onClick={() => setIsAuthenticated(true)}>Sign In</button>
    </>
  );
  return <div> {isAuthenticated ? <AuthNav /> : <MainNav />}</div>;
};

const App = () => {
  const [isAuthenticated, setIsAuthenticated] = useState(false);
  return (
    <div className="App">
      <Navbar auth={{ isAuthenticated, setIsAuthenticated }} />
    </div>
  );
};

@lasjorg If Navbar is a separate function than App (like I am showing above), is this the best way or would it be better to use React Context or Redux? It definitely makes sense to me to keep the authentication useState in App instead of in Navbar as there may be other components displaying certain information that would need to be authenticated before displaying.

1 Like

it starting work closer, but a better question is I want the navbar to appear in certain routes or pathname how can this be come accomplished? for the authnav I only want that to be in signup/login routes and for the mainnav I want that to show in the home routes etc?

The code I posted was a simple example just to show the conditional rendering.

The auth state should be available app-wide. So using context or some state management lib. You wouldn’t co-locate the auth state inside the navigation. But that is not to say you can’t pass and use some auth info in the navigation component.

I assume you are using react-router so you can take a look at the auth example they have.

https://github.com/remix-run/react-router/tree/dev/examples/auth

If the main navigation is behind a protected route it suggests to me that everything you can navigate to should be behind it, not just the navigation. Otherwise, people that know or guess the paths can just use the browser address bar to manually go to a route path.