score:49

Accepted answer

You need to bind context of this.

The line where you are binding your onClick handler:

onClick={this.showLeft}

Needs to be:

onClick={this.showLeft.bind(this)}

Otherwise when you're calling showLeft it can't access this.

score:0

Could be a this issue. try

showLeft = () => {
            this.refs.leftmenu.show();
        }

or

constructor() {
  super();
  this.showLeft = this.showLeft.bind(this);
}

score:0

You can also bind it like this to avoid eslint error of No .bind() or Arrow Functions in JSX Props:

class SidePanel extends BaseComponent {
    constructor(props) {
        super(props);
        this.showLeft = this.showLeft.bind(this);
        this.state = {
            error: false,
        };
    }

    showLeft() {
        this.refs.leftmenu.show();
    }


    render() {
        return(
            <div>
                <button onClick={this.showLeft}>Show Left Menu!</button>

                <Menu ref="leftmenu" alignment="left">
                    <MenuItem hash="first-page">First Page</MenuItem>
                    <MenuItem hash="second-page">Second Page</MenuItem>
                    <MenuItem hash="third-page">Third Page</MenuItem>
                </Menu>
            </div>
        );
    }
}

score:0

Your code is written in ES6. Unlike ES5, there is no auto binding in ES6.

So you have to explicitly bind the function to the component instance using this.functionName.bind(this).

Like so:

<button onClick={this.showLeft.bind(this)}>Show Left Menu!</button>

Without binding, when you click on the button, the this on the button refers to the button itself and not the function. So JavaScript tries to find refs on the button element, which gives you that error.

score:7

Change this:

<button onClick={this.showLeft}>Show Left Menu!</button>

To this:

<button onClick={::this.showLeft}>Show Left Menu!</button>`

Related Query

More Query from same tag