简体   繁体   中英

react-burger-menu isOpen prop not reacting to state change

My app uses react-burger-menu for a mobile only hamburger menu. When an item from the menu is clicked, I'd like the menu to close, but nothing happens. (Side note - if I set menuIsOpen: true in the parent component, it is indeed open on page load, and the first time I click a list item the sidebar does close but if I reopen it and then try it again nothing happens.)

Parent component ( full code ):

this.state = {
  menuIsOpen: false
};

// Gets called when an item in sidebar is clicked
handleVenuesListItemClick = venue => {
    this.setState({ menuIsOpen: false });
};

render() {
  return (
    <Sidebar
      menuIsOpen={this.state.menuIsOpen}
    />
  );

Child component ( full code ):

<Menu isOpen={this.props.menuIsOpen}>
  <div className="sidebar">

  </div>
</Menu>

View live version: https://nataliecardot.com/seattle-scoops/

Had this same issue. I think the problem is that you're not listening for the burger button to open the menu, and so the menuIsOpen state in the example doesn't ever get set to true. As a result, when a menu item is clicked, there is nothing to update-- menuIsOpen is still false.

To fix, you'll need to keep your parent component's state up to date with the menu's isOpen state. (The library's author has posted a few examples of this ). I am sure you can do this with hooks, but I'm inexperienced, and am not sure how. Here's an example class version, though.

import React, { Component } from 'react';
import { slide as Menu } from 'react-burger-menu'

class MobileExample extends Component {
  constructor(props) { 
    super(props)

    this.state = {
      menuOpen: false
    }

  this.handleStateChange=this.handleStateChange.bind(this);
  this.handleLinkClick=this.handleLinkClick.bind(this);  
  }

  handleStateChange(state) {
    this.setState({menuOpen:state.isOpen})
  }

  handleLinkClick(e) {
    this.setState({menuOpen:false})
  }

  render() {
    return (
      <Menu onStateChange={this.handleStateChange} isOpen={this.state.menu}>
          <nav>
            <ul>
              <a href="/" onClick={()=>this.handleLinkClick()}>Home</a>  
              <a href="/path-two" onClick={()=>this.handleLinkClick()}>Link text</a>
              <a href="/path-three" onClick={()=>this.handleLinkClick()}>Link text</a>
            </ul>
        </nav>
      </Menu>
    )
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM