FabricioG
FabricioG

Reputation: 3320

React in laravel is getting syntaxerror unexpected token

I realize this question has been asked a lot but I can't find an answer. Any help would be greatly appreciated, thank you!

According to a post in laracasts in regards to react in Laravel Jeffrey Way says: Just do:

mix.react('src', 'output');

And we'll install all the necessary Babel plugins and setup your .babelrc.

In my project I currently have a component and in my react mix file I have this:

mix.react('resources/assets/js/basicapp.js', 'public/js');

my basicapp.js file is a simple component setup like so:

require('./components/Reactapp');

When I run mix it creates an error: Module build failed: SyntaxError: Unexpected token (43:17)

  41 |   }
  42 | 
> 43 |   toggleSelected = (id, key) => {
     |                  ^
  44 |     let temp = [...this.state[key]]
  45 |     temp[id].selected = !temp[id].selected
  46 |     this.setState({

I've been racking my brain over this for two days now! Any help would be greatly appreciated.

EDIT: After checking there is no .babelrc file according to the instructions by Jeffrey Way this should automatically be done by laravel.

Upvotes: 1

Views: 1032

Answers (3)

Lex Soft
Lex Soft

Reputation: 2488

toggleSelected = (id, key) => {
......
}

You are using what is called class fields/properties syntax for your event handler. This syntax is an experimental feature which can only be used when you provide the following : @babel/plugin-proposal-class-properties
See proposal class properties

You need to install the plugin by using this command :

npm install --save-dev @babel/plugin-proposal-class-properties

Upvotes: 0

FabricioG
FabricioG

Reputation: 3320

After further review Laravel doesn't just work with es6. I had to add a .babelrc file and then add some dependencies to the package.json

I added this to package.json devDependencies:

"babel-cli": "^6.26.0",
"babel-eslint": "^8.2.6",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-stage-0": "^6.24.1",

this was already there:

"babel-preset-react": "^6.24.1",

in .babelrc file I added this:

{
    "presets": [
        "react",
        "stage-0",
        [
            "env",
            {
                "targets": {
                    "browsers": [
                        "last 2 versions",
                        "safari >= 7"
                    ]
                }
            }
        ]
    ],
    "plugins": [
        [
            "babel-plugin-transform-class-properties"
        ]
    ]
}

Upvotes: 1

michele
michele

Reputation: 23

I'd leave this as a comment but I don't have enough points to comment. But does it work if you don't use es6 syntax?

toggleSelected(id, key){}

Upvotes: 0

Related Questions