Jaeger
Jaeger

Reputation: 1754

Babel throws a syntax error on arrow function

I'm trying to adapt this code for a small project with React, but I'm having trouble, and I don't know how to fix this, because I don't know if this is the original code or my Babel that's buggy (like, missing a library or something), or if I can't because React.

So the thing is I had to adapt some functions because otherwise Babel would throw an unexpected token on them, i.e,

static propTypes = { // unexpected '='
  onRequestSort: PropTypes.func.isRequired,
  onSelectAllClick: PropTypes.func.isRequired,
  order: PropTypes.string.isRequired,
  orderBy: PropTypes.string.isRequired,
};

became

static get propTypes() {
    return {
        onRequestSort: PropTypes.func.isRequired,
        onSelectAllClick: PropTypes.func.isRequired,
        order: PropTypes.string.isRequired,
        orderBy: PropTypes.string.isRequired,
    }
}

and this:

handleRequestSort = (event, property) => { ... } // unexpected '='

became this:

handleRequestSort(event, property) { ... }

For my main issue, I replaced this:

createSortHandler = property => event => { // unexpected '='
    this.props.onRequestSort(event, property);
};

by this

createSortHandler(property) {
    return function (event) {
        this.props.onRequestSort(event, property);
    };
};

However, if I click on the arrow on the table that triggers the order's change, I get cannot read props of undefined. Otherwise, I get `unexpected token '=', as written in my code.

So my question is the following: is the original code buggy, is it my babel or is it something else? I'm currently on a Rails base with webpacker, but i don't believe this is the reason why I have these issues.

Upvotes: 4

Views: 3530

Answers (1)

Andrew Li
Andrew Li

Reputation: 57964

You're missing the babel-plugin-transform-class-properties plugin to transform the class properties which is experimental syntax (hence the unexpected token =). Include that in Babel configuration if you would like to use class properties for propTypes and class property arrow functions. The second error, that this.props is undefined is because you're using a regular function which this doesn't refer to the component. Return an arrow function instead:

createSortHandler(property) {
  return (event) => {
    this.props.onRequestSort(event, property);
  };
};

Upvotes: 4

Related Questions