简体   繁体   中英

How to toggle display state of a component in Astro

I have a Astro component <Header> defined. It has a menu button which should show/hide a component based on the click of this button. This is how I have defined my component:

---
let menuHidden = true;
---
<section id="header-all"
    class="container min-w-full bg-gradient-to-br from-blue-700 to-blue-500">
    <header class="container mx-auto px-5 flex items-center justify-between h-36">
        <button id="menuButton">
            <i class='lg:hidden bx bx-menu text-white text-4xl'></i>
        </button>
    </header>

    {!menuHidden &&
    <div class="container hidden lg:hidden mx-auto px-5">
        <nav class="flex flex-col py-5 rounded-lg bg-gray-100 px-10 text-gray-100 text-xl">
            <a href="#" class="py-3 text-2xl font-semibold text-gray-800 hover:bg-yellow-300 hover:rounded-lg px-5">Home</a>
        </nav>
    </div>
    }
</section>
<script is:inline>
    const menuButton = document.getElementById('menuButton');
    menuButton?.addEventListener("click", () => {
        menuHidden = !menuHidden;
        console.log("menu hidden: ", menuHidden);
    })
</script>

When i click on the button, i get following error in my console:

(index):904 Uncaught ReferenceError: menuHidden is not defined
    at HTMLButtonElement.<anonymous> ((index):904:9)

How can i achieve this in astro?

The easiest here is, in case the server does not need to know if the client menu is hidden or not, is to change your client event click to simply add an id to your menu container and

const menuContainer = document.getElementById('menuContainer');
menuContainer.classList.toggle("hidden")

It was not mentioned, but you might expect the menu state to persist across page reloads, Astro is an MPA framework, you could avoid that by turning it into an SPA (eg use React with Astro and put all in one page, or look for other Astro SPA solutions), but sticking to MPA conecept which is what Astro was designed to do, and have state sync between server and client will seem more complex that if it was an SPA that loads only a page once from the server.

Yet, it is possible in two ways to keep server/client state in sync, let's think of the menu state like if it was a counter (0 closed, 1 open)

Again as a warning, server/client sync might sound complex, which is due to MPA vs SPA concept.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM