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
Update
Simpler implementation using a React ref.
- Create a ref for the
Navbar.OffCanvas
component. - Create an
onClick
handler to access the attached ref, thebackdrop
element, and simulate a click event. - Add an
onClick
handler to eachLink
component to toggle theNavbar.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>
</>
);
};