How can I force bootstrap offcanvas navbar to close when I click on a link in react?

Viewed 116

I have a react app with a bootstrap offcanvas navbar that comes in from the right side when I click the hamburger. It works and closes when I click outside the offcanvas element or on the x inside the component, but when I click on a link it renders the new page but the navbar is still open. Is there a way I can force it to close when a user clicks on a link to a new page?

Here is the navbar code that is imported into the header which is imported into App.js:

import Container from 'react-bootstrap/Container';
import Nav from 'react-bootstrap/Nav';
import Navbar from 'react-bootstrap/Navbar';
import { LinkContainer } from 'react-router-bootstrap';
import Offcanvas from 'react-bootstrap/Offcanvas';

function OffcanvasNav() {
  return (
    <>
      {[false].map((expand) => (
        <Navbar key={expand} bg='light' expand={expand} className='mb-3'>
          <Container fluid>
            <Navbar.Brand to='/'>Denver Judo</Navbar.Brand>
            <Navbar.Toggle aria-controls={`offcanvasNavbar-expand-${expand}`} />
            <Navbar.Offcanvas
              id={`offcanvasNavbar-expand-${expand}`}
              aria-labelledby={`offcanvasNavbarLabel-expand-${expand}`}
              placement='end'
            >
              <Offcanvas.Header closeButton>
                <Offcanvas.Title id={`offcanvasNavbarLabel-expand-${expand}`}>
                  Denver Judo
                </Offcanvas.Title>
              </Offcanvas.Header>
              <Offcanvas.Body>
                <Nav className='justify-content-end flex-grow-1 pe-3'>
                  <LinkContainer to='/'>
                    <Nav.Link>Home</Nav.Link>
                  </LinkContainer>
                  <LinkContainer to='/schedule'>
                    <Nav.Link>Schedule</Nav.Link>
                  </LinkContainer>
                  <LinkContainer to='/about'>
                    <Nav.Link>About</Nav.Link>
                  </LinkContainer>
                </Nav>
              </Offcanvas.Body>
            </Navbar.Offcanvas>
          </Container>
        </Navbar>
      ))}
    </>
  );
}

export default OffcanvasNav;
1 Answers

I don't know if this is the best way to handle it but I added an onClick to each of the LinkContainers to set expend = '' and it works.

<LinkContainer to='/' onClick={() => (this.expand = '')}>
  <Nav.Link>Home</Nav.Link>
</LinkContainer>
<LinkContainer to='/schedule' onClick={() => (this.expand = '')}>
  <Nav.Link>Schedule</Nav.Link>
</LinkContainer>
<LinkContainer to='/about' onClick={() => (this.expand = '')}>
  <Nav.Link>About</Nav.Link>
</LinkContainer>
Related