Search code examples
javascriptreactjsif-statementreact-routerreact-link

Add If statement to Link in React Js


hello all I have a small issue I want to add a condition in the extension where it works like this: If you are on the home page, go to the relevant section But if we are on another page, such as the user page, then when I press any button in the navbar, it takes me to the home page.

   <nav id="nav-menu-container">
      <ul className="nav-menu">
        <li className="menu-active"> <Link  className="navbar-brand" to='/'>Home</Link></li>
        <li><a href="#about">About Us</a></li>
        <li><a href="#services">Services</a></li>
       
        <li><a href="#team">Team</a></li>

        {sessionStorage.getItem("username")!== null?<>
        <li><Link className="navbar-brand" to='/Contract'>Contarcts</Link></li>
        <li><Link  className="navbar-brand" to='/Userprofile'>{sessionStorage.getItem('username')} </Link></li>
        <li><button className="logout" onClick={logout} >LOGOUT</button></li></>:<>

{/* add if Condition to the Link that directs the extension  */}

        <li><Link  className="navbar-brand" to='/Signup'>Signup</Link></li>
        <li><Link  className="navbar-brand" to='/Login'>Login</Link></li></>}
      </ul>
    </nav>

if I am on a home page go to the specific section if I am not go to the homepage as simple as that.


Solution

  • Try this, this is kinda weird but it may work.

    Try adding slash (/) before every section in the href.

    something like this:

    <li><a href="/#about">About Us</a></li>
    

    So if you're not on homepage, you'll go back to the homepage when you click the link.