Home > Software engineering >  How to hide the offcanvas navbar when selecting the links inside of it using react scroll?
How to hide the offcanvas navbar when selecting the links inside of it using react scroll?

Time:04-26

Any idea on how to hide/back to its original state when selecting the links inside offcanvas using react scroll?

Below is my code and also here is the sandbox code Edit offcanvas-react-scroll (forked)

Update

Simpler implementation using a React ref.

  1. Create a ref for the Navbar.OffCanvas component.
  2. Create an onClick handler to access the attached ref, the backdrop element, and simulate a click event.
  3. Add an onClick handler to each Link component to toggle the Navbar.OffCanvas component hidden.

Code

const Header = () => {
  const offCanvasRef = useRef();
  const offsetValue = -56;

  const closeOffCanvas = () => offCanvasRef.current.backdrop.click();

  return (
    <>
      <Navbar bg="dark" variant="dark" expand={false} fixed="top">
        <Container fluid>
          <Navbar.Brand href="#">Navbar Offcanvas</Navbar.Brand>
          <Navbar.Toggle aria-controls="offcanvasNavbar" />
          <Navbar.Offcanvas
            ref={offCanvasRef}
            ...
          >
            <Offcanvas.Header closeButton>
              ...
            </Offcanvas.Header>
            <Offcanvas.Body>
              <Nav className="justify-content-end flex-grow-1 pe-3 offcanvas--menu">
                <Link
                  ...
                  onClick={closeOffCanvas}
                >
                  Home
                </Link>
                <Link
                  ...
                  className="p-3 border-bottom border-dark text-decoration-none"
                  onClick={closeOffCanvas}
                >
                  About
                </Link>
                <Link
                  ...
                  onClick={closeOffCanvas}
                >
                  Contact
                </Link>
              </Nav>
            </Offcanvas.Body>
          </Navbar.Offcanvas>
        </Container>
      </Navbar>
    </>
  );
};

Edit how-to-hide-the-offcanvas-navbar-when-selecting-the-links-inside-of-it-using-rea (with Ref)

  • Related