0

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?

4
  • @JoshKelley Sorry, typo. Fixed. Commented Apr 12, 2017 at 2:06
  • 1
    You are not returning valid jsx from your component. See here for learning about valid jsx. Commented Apr 12, 2017 at 2:12
  • Everything is wrong :p this is not valid JSX ! Not even valid react. Commented Apr 12, 2017 at 2:16
  • I'll leave this code up like this so anyone making the same mistake I was that reaches this question may figure out how to do it correctly with @JoshKelley ´s answer. Commented Apr 12, 2017 at 23:48

1 Answer 1

2
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.)

Sign up to request clarification or add additional context in comments.

3 Comments

I used your example but I still get the same error when running Webpack. Now it points to the equal sign in > 5 | handleAdd = e => { ..
@feners - Did you see the docs I linked to about property initializer syntax? It's not yet standardized, so you'll need an extra Babel plugin to make it work.
Thanks for pointing out my mistakes and detailing how to solve them. I got it to work with your example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.