feners
feners

Reputation: 675

How to fix "Module build failed: SyntaxError: Unexpected token" error when using React and Webpack?

I'm using Webpack and React to build a simple Shopping Cart for a webshop. For some reason I get this error when I add my add to cart function to my .js file:

ERROR in ./js/views/Cart.js
Module build failed: SyntaxError: Unexpected token

And it points to var productID in my js code.

My Cart.js looks like:

import React, { Component } from 'react';

export default class Cart extends Component {
  render() {
    return (
      <div className='Cart' id='Cart'>
        <iframe src="./logo.pdf" width="425" height="425"></iframe>
        $("#addit").click(function(){
            var productId = $("#productId").val();
            var productName = $("#productName").val();
            var productQuantity = $("#productQuantity").val();
            var data = {
              'product_id': productId,
              'product_name': productName,
              'quantity': productQuantity
            }; 

            $.post("/cart/add", data, showDone);
          });

          var showDone = function() {
            /* Make something happen here*/
          }
      </div>
    );
  }
}

My Webpack config is:

const path = require('path');

module.exports = {
  context: __dirname + "/app",

  entry: {
    javascript: "./js/app.js",
    html: "./index.html",
  },

  output: {
    filename: "app.js",
    path: __dirname + "/dist",
  },

  resolve: {
    extensions: ['', '.js', '.jsx', '.json'],
    root: path.resolve(__dirname, './app/js'),
  },

  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        include: [
          path.resolve(__dirname, "app")
        ],
        loaders: ["react-hot", "babel-loader"],
      },
      {
        test: /\.html$/,
        loader: "file?name=[name].[ext]",
      }
    ],
  },
}

What is wrong with my code that is causing this error?

Upvotes: 0

Views: 7110

Answers (1)

Josh Kelley
Josh Kelley

Reputation: 58402

export default class Cart extends Component {
  render() {
    return (
      <div className='Cart' id='Cart'>
        <iframe src="./logo.pdf" width="425" height="425"></iframe>
        $("#addit").click(function(){});
      </div>
    );
  }
}

This is not how React works. While it's true that React's JSX looks like HTML, it's not the same thing; instead, it's transformed (by Babel) into JavaScript instructions to create React elements that render to that HTML.

Trying to put jQuery JavaScript into your JSX isn't going to work. (And it wouldn't have much purpose - why tell your JavaScript to create React elements that create JavaScript, instead of just writing JavaScript?)

As a starting point, try something like this instead, putting the necessary logic into React):

export default class Cart extends Component {
  handleAdd = e => {
    // Look up productId, productName, productQuantity
    // Use React refs for this, or (better) have those components
    // store their values via onChange or similar someplace where this
    // component can see it.
    //
    // Issue AJAX - it's okay to use jQuery here, but jQuery's a big
    // dependency just for AJAX.
    //
    // etc.
  };

  render() {
    return (
      <div className='Cart' id='Cart'>
        <iframe src="./logo.pdf" width="425" height="425"></iframe>
        <button onClick={this.handleAdd} id="addit">Add to cart</button>
      </div>
    );
  }
}

(This handleAdd uses the property initializer syntax described in the React docs.)

Upvotes: 2

Related Questions