Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing error: Unexpected token const

I am currently setting up a meteor application and I am using eslint and babel, but I get the following error for the following code snippet:

const Navigation = props => (
  const classes = props.classes;

  return (
    <div className={classes.root}>
    </div>
  )
);

Error:

2:4 - Parsing error: Unexpected token const

I have recreated my eslint config here. My .babelrc config is the following:

{
  "presets": ["env", "react"]
}
like image 424
Tom Avatar asked Sep 18 '17 15:09

Tom


2 Answers

It's because you are using the concise body of an arrow function and that expects the expression inside () and not a statement. To use a statement you need to use block body by using {} instead of ().

Like this:

const Navigation = props => {
  const classes = props.classes;

  return (
    <div className={classes.root}>
    </div>
  )
};

As per MDN Doc:

Arrow functions can have either a "concise body" or the usual "block body".

In a concise body, only an expression is needed, and an implicit return is attached. In a block body, you must use an explicit return statement.

like image 69
Mayank Shukla Avatar answered Oct 16 '22 23:10

Mayank Shukla


@Mayank Shukla has the solution, but I would like to add that you could also do:

const Navigation = ({classes}) => (
  <div className={classes.root}>
  </div>
);

The ({classes}) part is called "object destructuring" and basically means that you're extracting the classes property from the props parameter that your function receives.

You could do this with any number of parameters. For example:

const Navigation = ({classes, children}) => (
  <div className={classes.root}>
    {children}
  </div>
);

Take a look at the MDN documentation for more info:

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

like image 40
Chris Avatar answered Oct 16 '22 21:10

Chris