Home > Software design >  How to show or hide a button depending on the page in React
How to show or hide a button depending on the page in React

Time:11-20

I'm actually kinda new to React, and I'm still learning, so I cannot figure out how to display my button depending on which page I currently am on my app. I'm using Router v6. This is my Router with my components inside:

     <Router>
        <Navbar />
        <Routes>
          <Route
            path="/"
            element={<HomePage />} />
          <Route
            path="/CountryPage"
            element={<CountryPage />} />
        </Routes>
      </Router>

This is my navbar:

const Navbar = () => {
  return (
    <nav className="navbar-container">
      <div>
        <div>
          <ul className="navbar">
            <li>
              <Link to="/" className="home"> <AiOutlineLeft /> </Link>
            </li>
            <li data-testid="tab-name">
              Current Tab
            </li>
            <li>
              <BsFillGearFill className="settings" />
            </li>
          </ul>
        </div>
      </div>
    </nav>
  );
};

So all I want is to display the button that is <li> <Link to="/" className="home"> <AiOutlineLeft /> </Link> </li> only if I am not in the HomePage So if I am in the Homepage I don't want to show anything.

Any idea?

CodePudding user response:

window.location.href is a out-of-the-box JS method you should use if you don't have your routing managed by some better library (like react router). Also, here, instead of just the pathname, you actually have to check the entire URL. So your corrected code for this method would be

{ window.location.href !=== "yoursubdomian.yourdomain.extension/" && <li> <Link to="/" className="home"> <AiOutlineLeft /> </Link> </li>

My advice would be that try a systematic approach using the provisions React Router itself provides

Use the useLocation() hook to extract the pathname of the current route and check it for rendering the <Link/>

const Navbar = () => {
  const location = useLocation()
 
  return (
    <nav className="navbar-container">
      <div>
        <div>
          <ul className="navbar">
            {location.pathname !=="/" && 
               <li>
                 <Link to="/" className="home"> <AiOutlineLeft /> </Link>
               </li>
            }
            <li data-testid="tab-name">
              Current Tab
            </li>
            <li>
              <BsFillGearFill className="settings" />
            </li>
          </ul>
        </div>
      </div>
    </nav>
  );
};
  • Related