Here's how to create a responsive navigation menu in Astro. Let's start by adding an HTML block for the navbar.
<Container>
<nav>
<div>
<a href="/">
<img src="../assets/logo.jpg" alt="Logo" width={132} height={52} />
</a>
<button id="menu" aria-label="Toggle Menu">
<svg class="w-6 h-6 fill-current" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path class="navmenu-toggle" fill-rule="evenodd"
d="M4 5h16a1 1 0 0 1 0 2H4a1 1 0 1 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2z">
</path>
<path class="navmenu-toggle hidden" fill-rule="evenodd" clip-rule="evenodd"
d="M18.278 16.864a1 1 0 0 1-1.414 1.414l-4.829-4.828-4.828 4.828a1 1 0 0 1-1.414-1.414l4.828-4.829-4.828-4.828a1 1 0 0 1 1.414-1.414l4.829 4.828 4.828-4.828a1 1 0 1 1 1.414 1.414l-4.828 4.829 4.828 4.828z">
</path>
</svg>
</button>
</div>
<div class="navmenu-toggle hidden">
<div>
{mobilemenu.map((item, index) => (
<a href={item.href} target={item.external ? "_blank" : "" } rel={item.external ? "noopener" : "" }>
{item.label}
</a>
))}
</div>
</div>
</nav>
</Container>
The above code will add a navbar in Astro. For simplification, I have removed all un-necessary styles. You might want to add those to display it perfectly.
Now, Let's add the required frontmatter & Astro props.
---
import Container from "@components/container.astro";
const navmenu: Menu[] = [{
label: "Home",
href: "/",
},
{
label: "About",
href: "/about",
},
{
label: "Contact",
href: "/contact",
},
];
---
Now, let's add our javascript to toggle the menu & our hamburger icon.
<script>
const menuButton = document.getElementById("menu");
menuButton.addEventListener("click", () => {
[...document.querySelectorAll(".navmenu-toggle")].forEach((Element) => {
Element.classList.toggle("hidden");
});
});
</script>
That's it. We have our working navigation menu bar with toggle.