0

I have a syntax error in my code, and I'm not sure why. Does it have to do with the way I used refs?

export default class ToggleMenu extends React.Component {

  showRight: function() {
    this.refs.right.show();
  }

  render() {
    return (
      <div>
      <button onClick={this.showRight}>Show Left Menu!</button>
      {/*  
        <Menu ref="right" alignment="right">
          <MenuItem hash="1">First</MenuItem>
          <MenuItem hash="2">Second</MenuItem>
          <MenuItem hash="3">Third</MenuItem>
        </Menu> 
      */}
      </div>
    );
  }
}

Here is the error:

./src/components/ToggleMenu/ ToggleMenu.js Module build failed: SyntaxError: Unexpected token (13:14)

showRight: function() {
  this.refs.right.show();  
}
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
Alex
  • 457
  • 6
  • 12
  • 27

1 Answers1

1

You're getting object literals and classes mixed up. Your code is inside a class, not an object literal, so you must use method definition syntax like you did with render. Classes can only contain prototypal methods and a constructor (as of ECMAScript 2015):

showRight() {
  this.refs.right.show();
}

Or else it will be interpreted as a label and a function declaration, but function declarations with the function keyword cannot be in class bodies thus the syntax error:

showRight: //label
function() { //function declaration, not valid in class body!
    ...
}

Also, make sure to bind(this) to your methods so that this refers to the component and not the global scope's this value:

constructor(props) {
  super(props);
  this.showRight = this.showRight.bind(this);
}

Read more about class bodies at MDN.


Regarding your use of refs, you should use a callback instead of a plain string:

<Menu ref={right => this.right = right} alignment="right">

Then in your showRight:

this.right.hide();
Andrew Li
  • 55,805
  • 14
  • 125
  • 143
  • ok that make sense thank u but at least why im geting the next error: uncaught (in promise) TypeError: Cannot read property 'bind' of undefined – Alex Jun 02 '17 at 16:23
  • @Alex are you sure you're putting it in the constructor? – Andrew Li Jun 02 '17 at 16:26
  • `export default class ToggleMenu extends React.Component { constructor(props) { super(props); this.showRight = this.showRight.bind(this); } render() { return (
    {/* this.right = right} alignment="right"> First Second Third */}
    ); } }` yes im sure .. can u please tell me whats wrong
    – Alex Jun 02 '17 at 16:33
  • 1
    Well, there is no `showRight` function in your example. – Sulthan Jun 02 '17 at 16:42