APixel Visuals
APixel Visuals

Reputation: 1648

React.JS - Calling a function on `onClick` event causes `this` to be undefined in function

I have the following React.JS (Next.JS) code:

export default class NavBar extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            menuOpen: false
        };
    }

    render() {
        return <img id="menu-button" src="/static/menu.svg" onClick={this.toggleMenu}></img>;
    }

    toggleMenu() {
        this.setState({ menuOpen: this.state.menuOpen ? false : true });
    }

};

However, when the image is clicked, and toggleMenu is called, I get an error saying that this is undefined. This makes sense, since the function is being put into the onClick event, but how can I fix this?

Upvotes: 1

Views: 148

Answers (1)

Default
Default

Reputation: 16488

You need to either explicitly bind this context to your function like:

this.toggleMenu.bind(this)

or re-define your toggleMenu function using arrow notation which does this implicitly:

toggleMenu = () => {
  // method body here...
}

Upvotes: 3

Related Questions