kawnah
kawnah

Reputation: 3404

ReactJS - Module build failed: SyntaxError: Unexpected token react components not rendering

I return a react component like this:

return (
    <section style={styleObj} id="Profile" >
      <h2 className="colorHeader">{this.state.color}</h2>
      <input id="colorInput" placeholder="Enter Hex Code Here" onChange={this.changeColor.bind(this)}/>
      <div id="slider"></div>
    </section>
  );

This is resulting in:

ERROR in ./app/js/modules/colorpicker.js
Module build failed: SyntaxError: Unexpected token (31:4)

  29 |
  30 |   return (
> 31 |     <section style={styleObj} id="Profile" >
     |     ^
  32 |       <h2 className="colorHeader">{this.state.color}</h2>
  33 |       <input id="colorInput" placeholder="Enter Hex Code Here" onChange={this.changeColor.bind(this)}/>
  34 |       <div id="slider"></div>

To my understanding as of now, you need a babel transpiler to convert this correctly. The relevant part of my webpack config looks like this:

module: {
  rules: [{
      test: /\.js$/,
      use: 'babel-loader'
    }]
  },

I did some more research and tried this:

loaders: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader',
        query  :{
          presets:['react','es2015']
        }
        exclude: /node_modules/
      }
    ]

This returns:

Module build failed: Error: Couldn't find preset "react" relative to directory

So I referenced this question and tried this:

{
  "presets": ["es2015", "react"]
}

Still get:

Module build failed: Error: Couldn't find preset "react" relative to directory

How do I get react components to render correctly with a webpack config?

The linked answer suggests npm ls babel-preset-es2015 which gets:

[email protected] /projects/new-platform-prototype └── [email protected]

Upvotes: 0

Views: 1397

Answers (2)

Damian
Damian

Reputation: 1553

loaders: [
  {
    test: /\.jsx?$/,
    loader: 'babel-loader',
    query  :{
      presets:['react','es2015']
    }
    exclude: /node_modules/
  }
]

try changing jsx to js

  loaders: [
  {
    test: /\.js?$/,
    loader: 'babel-loader',
    query  :{
      presets:['react','es2015']
    }
    exclude: /node_modules/
  }
]

Upvotes: 0

Bojan Ivanac
Bojan Ivanac

Reputation: 1180

npm install -D babel-preset-react babel-preset-es2015

This should fix your problem.

Upvotes: 1

Related Questions