Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React onClick event not firing when function is passed to child [duplicate]

I have a pretty simple React component where I pass the callback for the onClick event to a child element; however, the onClick event does not seem to ever fire. The class is below, HamburgerMenu and Hamburger are correctly imported/rendered with no events existing on those components.

export default class AppHandler extends React.Component {
  componentWillMount() {
    this.state = {
      menuOpen: false
    };
  }
  render() {
    return (
      <div>
        <HamburgerMenu menuOpen={this.state.menuOpen} />
        <div className="content">
          <nav>
            <Hamburger onClick={this.onMenuChange.bind(this)} />
          </nav>
        </div>
      </div>
    );
  }
  onMenuChange() {
    console.log('onMenuChanged');
    this.setState({ menuOpen: !this.menuOpen });
  }
};

I can get it to work if in the Hamburger component I set another onClick event on the root element and then set this.props.onClick as that event handler but that seems like it's unnecessary from everything I have saw.

Any guidance? Thank you!

like image 218
BenM Avatar asked Sep 18 '15 01:09

BenM


1 Answers

So this did end up being me not understanding where the onClick event is getting attached. Since the component itself is not really an actual element when setting onClick={this.onMenuChange(this)} I am only setting prop.onClick for the child element Hamburger. In order to actually get the bind to work I do have to set onClick={this.props.onClick} on the root element of the Hamburger component.

like image 168
BenM Avatar answered Sep 28 '22 09:09

BenM