Skip to content
Advertisement

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

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 https://codesandbox.io/.

App.js

JavaScript

Header.js

JavaScript

Content.js

JavaScript

Im using the ff:
react 17.0.2
react-router-dom 6.2.2
react-scroll 1.8.7
react-bootstrap offcanvas 2.1.2 https://react-bootstrap.github.io/components/offcanvas/

I’m not sure if I missed something like useState/useEffect or an attribute to make it work.

Advertisement

Answer

I’m not a fan of bootstrap and I’m sure there’s a more vanilla Javascript/boostrap method for achieving this, but here’s a simple implementation using some local state.

  1. Add a show state that can be toggled true/false.
  2. Add an onClick handler to the Navbar.Toggle component to handle opening the OffCanvas component.
  3. Add the show and onHide props to the Navbar.Offcanvas to handle showing/hiding the OffCanvas component.
  4. Add an onClick handler to each Link component to toggle the show state.

Code

JavaScript

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

JavaScript

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

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement