skip to Main Content

I am trying to show and hide a navbar based on whether a variable is set to true or false. I am able to get the Navbar to show/hide however, my problem happens when I try to set the Navbar to always show at the large breakpoint.

In other words, I want the navbar to be constantly showing at the large breakpoint and above even if the variable controlling the navbar is set to false. However, this does not happen. I can’t figure out what is wrong with my code. Can someone please help me?

My code is here:

 <div className={`lg:!relative z-50 ${showNavBar ? "absolute" : "hidden"} `}>
      <Navbar showNavBar={showNavBar} handleNavBar={handleNavBar} />
</div>

2

Answers


  1. You need to override the display: none applied by hidden when showNavBar is falsy by using a display utility, like block for display: block:

    function Navbar() {
      return (
        <React.Fragment>
          Foo
        </React.Fragment>
      );
    }
    
    const showNavBar = false;
    const handleNavBar = null;
    
    ReactDOM.createRoot(document.getElementById('app')).render(
      <div className={`lg:!relative lg:block z-50 ${showNavBar ? "absolute" : "hidden"} `}>
        <Navbar showNavBar={showNavBar} handleNavBar={handleNavBar} />
      </div>
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.2.0/umd/react.production.min.js" integrity="sha512-8Q6Y9XnTbOE+JNvjBQwJ2H8S+UV4uA6hiRykhdtIyDYZ2TprdNmWOUaKdGzOhyr4dCyk287OejbPvwl7lrfqrQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.2.0/umd/react-dom.production.min.js" integrity="sha512-MOCpqoRoisCTwJ8vQQiciZv0qcpROCidek3GTFS6KTk2+y7munJIlKCVkFCYY+p3ErYFXCjmFjnfTTRSC1OHWQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script src="https://cdn.tailwindcss.com/3.3.2"></script>
    
    <div id="app"></div>
    Login or Signup to reply.
  2. You can prefix the variables inside the brackets with "max-lg" so they only apply below the large breakpoint:

    <div class={`lg:absolute ${showNavBar ? "max-lg:hidden" : "max-lg:absolute"} `}>
          <Navbar showNavBar={showNavBar} handleNavBar={handleNavBar} />
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search