Changing the visibility of a component in Astro: A step-by-step guide

I have created an Astro component called <Header>. Within this component, there is a menu button that should toggle the visibility of another component when clicked. Below 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>

Upon clicking the button, I encounter the following error in the console:

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

I am seeking advice on how to achieve this functionality within Astro.

Answer №1

When considering whether the server needs to know if the client menu is hidden or not, a simple solution is to modify your client event click by adding an id to your menu container:

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

If you want the menu state to persist across page reloads, you can explore different approaches within Astro. While turning it into a single-page application (SPA) could avoid this issue, sticking with the multi-page application (MPA) concept may seem more complex in terms of state synchronization between server and client.

There are two ways to keep server/client state in sync, such as treating the menu state like a counter (0 for closed, 1 for open):

It is important to note that achieving server/client sync may appear challenging, especially when comparing MPA versus SPA concepts.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for disabling automatic browser scrolling to a specific div ID?

I have a webpage with a vertical accordion in the center to display content. Upon loading the page, the accordion is centered. However, when a user clicks on a tab, the entire page scrolls up, moving the tab to the top of the browser. Is there a way to pre ...

Preventing DIV Selection in TinyMCE with IE9 using Width/Height and ContentEditable

When working with TinyMCE (3.5.4.1) on IE9, an issue arises when a DIV with specified Height and/or Width is placed in the content. In such cases, IE treats it as a contenteditable DIV to some extent. This results in the DIV getting highlighted when the u ...

Utilizing AJAX in Datatables- Effortlessly sharing a URL link to a designated page

I've recently encountered an issue while using Datatables and AJAX to retrieve data from my Rails server. The problem arises when I try to share a specific page (let's say page 2) with another user who is also using Datatables. Due to the paginat ...

AngularJS ui-router resolve function may not successfully return a custom value

While attempting to preprocess some data before navigating to my page, I am forcefully resolving a promise, converting it into a custom object, and then trying to return the custom object to my resolve object. .state("trip.detail", { ...

Unable to launch Google Maps in modal box

I want to implement loading the Google Maps .js API within a Bootstrap 3 modal box upon clicking a link, and then opening the modal box using the Google Maps initialize method. Here is an example of how this should work: HTML: <a data-toggle="modal" h ...

Ways to update or incorporate new data within JavaScript

I'm currently experimenting with ways to incorporate additional text or even AdSense into what I believe is a .js file. There's an operational lightbox feature with a descriptive caption at the bottom, and that caption is what I want to modify. ...

The node application route appears to be malfunctioning

Recently delving into the world of node JS, I encountered an issue while working on my application with the following 3 files. http.createServer(app).listen(**app.get('port')**, function(){ The error message reads 'undefined is not a func ...

Form containing no field names using the multipart/form-data format

Initially, I had an HTML form set up to send information to a nodejs backend. When attempting to add file uploads to the same form, I needed to modify the enctype from its default value (application/x-www-form-urlencoded) to enctype='multipart/form-da ...

Incorporate the leaflet Draw feature into your Angular 2 application

I am a newcomer to Angular2, created using Cli. While I successfully imported Leaflet into my Angular2 project without any Angular2 directives, I am struggling to do the same with the Leaflet Draw extension. I haven't been able to make Draw work. In e ...

AngularJS - encountering a 404 error when reloading the page after removing the Hashbang

After taking out the hashbang from my routes by using $locationProvider.html5Mode(true); Now, when I go to a page like "domain.com/download", it works. But if I refresh this same page, I get a 404 Error. URLs like "domain.com/download" can only be acce ...

Delete local data storage in Angular 2 upon closing the window

After the user logs in, I store their token in local storage so that it is accessible across all tabs. However, I need to remove this token from local storage when the user closes the browser or window. What is the best way to clear local storage upon clo ...

Unable to properly map coordinates onto the canvas

This camera capture pen is designed to send the exact source image coordinates to the canvas based on the mouseX and mouseY positions, acting as a crop tool. For the full code source, visit: https://codepen.io/Mahmoud-Zakaria/pen/QKmZBO <a href="#mod ...

What is the best way to enhance a react-bootstrap component with TypeScript?

Currently, I am utilizing <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6f1d0a0e0c1b420d00001b1c1b1d0e1f2f5e415f415f420d0a1b0e415e5b">[email protected]</a> and delving into the development of a customized Button ...

Is there a way to remove specific content from a media recorder?

I have implemented the getUserMedia and MediaRecorder APIs to capture user videos. Now, I am trying to figure out how to add a button that allows users to delete the last part of their recorded stream if they paused while recording. Unfortunately, I have ...

Unable to construct React/Next project - identified page lacking a React Component as default export (context api file)

When attempting to compile my Next.js project, I encountered an error message in the terminal: Error: Build optimization failed: found page without a React Component as default export in pages/components/context/Context The file in question is utilizing ...

Guide on Testing the Fetch Functionality of useEffect Using Jest in React

Can someone assist me with testing my useEffect Fetch using Jest in React? I've been struggling to make it work and tried various solutions without success. This is my first time using Jest, and I'm currently integrating it into my project. Belo ...

To successfully display the data on my ChartJS Line graph, I have to first click on the color legend

I am currently using Chart JS to visualize sensor data retrieved from a firebase firestore database. I've come across an unusual issue where my chart fails to display the data initially >> https://i.sstatic.net/qD6Sd.jpg but after performing two ...

Display the information contained within an array in a table using React

I have two arrays: one named formData and the other state array. const [formData, setFormData] = useState([]); let ure = [{}] useEffect(() => { axios .get("/api/listUre") .then((res) => { console.log(res.data ...

What is the reason the 'Add' type does not meet the 'number' constraint?

I experimented with type gymnastics using Typescript, focusing on implementing mathematical operations with numeric literals. First, I created the BuildArray type: type BuildArray< Length extends number, Ele = unknown, Arr extends unknown ...

Executing the `writeFile` and `writeFileSync` functions in the Express.js route handler with Node.js causes the front-end page to automatically reload

Encountering an issue with my code where the page unexpectedly reloads when communicating with my backend app. The backend app utilizes functions from the fs module, specifically writeFile/writeFileSync. Oddly enough, when I eliminate these function calls, ...