[javascript] ReactJS: "Uncaught SyntaxError: Unexpected token <"

I am trying to get started building a site in ReactJS. However, when I tried to put my JS in a separate file, I started getting this error: "Uncaught SyntaxError: Unexpected token <".

I tried adding /** @jsx React.DOM */ to the top of the JS file, but it didn't fix anything. Below are the HTML and JS files. Any ideas as to what is going wrong?

HTML

<html>
  <head>
    <title>Page</title>
    <script src="http://fb.me/react-0.12.2.js"></script>
    <script src="http://fb.me/JSXTransformer-0.12.2.js"></script>
    <script src="http://code.jquery.com/jquery-1.10.0.min.js"> </script>
    <script src="./lander.js"> </script>
  </head>
  <body>
    <div id="content"></div>
    <script type="text/jsx">
        React.render(
            <Lander />,
            document.getElementById('content')
        );
    </script>
  </body>
</html>

JS

/**
 * @jsx React.DOM
 */
var Lander = React.createClass({
    render: function () {
        var info = "Lorem ipsum dolor sit amet... ";
        return(
            <div>
                <div className="info">{info}</div>
            </div>
        );
    }
});

EDIT: I realized that I need to add type="text/jsx" to the script tag which includes my lander code. However, after adding this and reloading I get this warning

"You are using the in-browser JSX transformer. Be sure to precompile your JSX for production - http://facebook.github.io/react/docs/tooling-integration.html#jsx"

followed by this error:

"XMLHttpRequest cannot load file:///Users/.../lander.js. Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https, chrome-extension-resource."

it seems like there is something else that I need to do in order to get in browser jsx transform working, but I'm not sure what it is.

EDIT: OOOOH do I need to host it using MAMP or something?

This question is related to javascript html reactjs react-jsx

The answer is


Add type="text/babel" as an attribute of the script tag, like this:

<script type="text/babel" src="./lander.js"></script>

Add type="text/babel" to the script that includes the .jsx file and add this: <script src="https://npmcdn.com/[email protected]/browser.min.js"></script>


If you have something like

Uncaught SyntaxError: embedded: Unexpected token

You probably missed a comma in a place like this:

  var CommentForm = React.createClass({
  getInitialState: function() {
      return {author: '', text: ''};

  }, // <---- DON'T FORGET THE COMMA

  render: function() {
      return (
      <form className="commentForm">
          <input type="text" placeholder="Nombre" />
          <input type="text" placeholder="Qué opina" />
          <input type="submit" value="Publicar" />
      </form>
      )
  }
  });

The code you have is correct. JSX code needs to be compiled to JS:

http://facebook.github.io/react/jsx-compiler.html


In addition to Dee Jee solution, After trying out his solution, My error never went.

I noticed(after two days of head scratch) that the browser has cached the files improperly.

  • My browser wasn't able to load the preview of the cached files and status code from express was 301.
  • In the networks tab of the browser dev tools, I get that those files are server from disk cache.

Solution

Remove the cached files. By clearing the browser history in a span of 1 hour, so that all the cached files get deleted.


Try adding in webpack, it solved the similar issue in my project. Specially the "presets" part.

module: {
    loaders: [
        {
            test: /\.jsx?/,
            include: APP_DIR,
            loader: 'babel',
            query  :{
                presets:['react','es2015']
            }
        },

If you are getting an error like this :

SyntaxError: embedded: Unexpected token (107:9) 105

It could be you are missing a curly bracket


JSTransform is deprecated , please use babel instead.

<script type="text/babel" src="./lander.js"></script>

I have the same issue with you and I have change something in my server

you might try this

const root = require("path").join(__dirname, "./build");
app.use(express.static(root));
app.get("*", (req, res) => {
  res.sendFile("index.html", { root });
});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to reactjs

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0 TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app Template not provided using create-react-app How to resolve the error on 'react-native start' Element implicitly has an 'any' type because expression of type 'string' can't be used to index Invalid hook call. Hooks can only be called inside of the body of a function component How to style components using makeStyles and still have lifecycle methods in Material UI? React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function How to fix missing dependency warning when using useEffect React Hook? Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

Examples related to react-jsx

Best practice when adding whitespace in JSX Render Content Dynamically from an array map function in React Native Warning: Failed propType: Invalid prop `component` supplied to `Route` How to pass props to {this.props.children} Expected corresponding JSX closing tag for input Reactjs Why calling react setState method doesn't mutate the state immediately? Can you force a React component to rerender without calling setState? React / JSX Dynamic Component Name How to loop and render elements in React.js without an array of objects to map? ReactJS: "Uncaught SyntaxError: Unexpected token <"