Max T
Max T

Reputation: 1455

Close menu after selecting an anchor link React and Gatsby

I have a hamburger nav that uses Gatsby's Link and navigates throughout the website. It works as intended, but if I'm on the same page as an anchor element that I'm clicking, the menu doesn't close. If I close it I can see that it navigated to where it needed to be.

When I add the onClick function then it overwrites the navigation, so the menu closes, but it doesn't navigate anywhere. How to solve this?

import React, { useState } from "react"
import { string } from "prop-types"

import { Link } from "gatsby"

import styles from "./styles.module.less"

const Navbar = ({ siteTitle, navColor }) => {
  const [isHidden, showNavigation] = useState(true)

  const links = (
    <div className={styles.links}>
      <Link to="/about">About</Link>
      <Link to="/people">People</Link>
      <Link to="/#work">Work</Link>
      <Link to="/careers">Careers</Link>
      <Link to="/contact-us">Contact</Link>
    </div>
  )

  const handleMenuToggle = e => {
    e.preventDefault()
    showNavigation(!isHidden)
  }
  let nvColor = navColor ? navColor : "translate"
  let logo = navColor ? blackLogo : whiteLogo
  return (
    <>
      <header data-component="Navbar" className={styles.Navbar}>
        <Link to="/" className={styles.logo} title={siteTitle}>
          <img src={logo} alt={siteTitle} />
        </Link>
        <a
          className={styles.menu}
          href="#main-nav"
          title="View menu"
          onClick={handleMenuToggle}
          style={{ color: nvColor }}
        >
          …
        </a>
      </header>
      <div>
        <nav id="main-nav" className={styles.MainNav} hidden={isHidden}>
          <div className={styles.blocks}>
            <div className={styles.LeftNav}>
              <a
                onClick={handleMenuToggle}
                title="Hide menu"
                href="#"
                className={styles.close}
              >
                <img src={close} alt="Hide menu" />
              </a>

              {links}
            </div>




          </div>
        </nav>
      </div>
    </>
  )
}

Navbar.propTypes = {
  siteTitle: string,
}

export default Navbar

Upvotes: 3

Views: 1468

Answers (1)

Nick
Nick

Reputation: 16576

You simply need to stop preventing default behavior

const handleMenuToggle = e => {
  e.preventDefault() // Remove this line
  showNavigation(!isHidden)
}

Upvotes: 2

Related Questions