Stef
Stef

Reputation: 11

React issue - @ is an unexpected token

I'm trying to implement react-keydown which can be found here: https://github.com/glortho/react-keydown using the following code example:

import React from 'react';
import keydown, { Keys } from 'react-keydown';

class MethodDecoratorExample extends React.Component {
  constructor( props ) {
    super( props );
    this.state = {
      hello: false
    };
  }

  @keydown( 'enter' )
  toggleHello() {
    this.setState( { hello: !this.state.hello } );
  }

  render() {
    return (
      <div>
        <h3>Method Decorator Example</h3>
        <div>Press the <strong>enter</strong> key to toggle hello.</div>
        { this.state.hello &&
          <h1>Enter is key code {Keys.enter}!</h1>
        }
        <div>And click again outside box to see scoping.</div>
      </div>
    );
  }
}

When I try this I get an unexpected token error on the @. I have no clue how to solve this.

What am I missing?

Thanks

Upvotes: 0

Views: 747

Answers (2)

iamsisar
iamsisar

Reputation: 101

Babel 6 no longer supports ES decorator syntax out of the box so you need to install the babel-plugin-transform-decorators-legacy plugin.

Install babel-plugin-transform-decorators-legacy

npm install --save-dev babel-plugin-transform-decorators-legacy

Add the plugin in your .babelrc

{
  "plugins": [
    "transform-decorators-legacy"
  ]
}

or

add the loader directly in your webpack.config.js

{
  test: /\.jsx?$/,
  loader: 'babel',
  query: {
    cacheDirectory: true,
    plugins: ['transform-decorators-legacy' ]
  }
}

Upvotes: 4

Stef
Stef

Reputation: 11

I found the answer here: How do I get decorators working with babel & webpack?

Thanks to @cbll for mentioning decorators, because I did not know that that is the correct term. Helped me with searching for solutions

Upvotes: 0

Related Questions