Silvio S.
Silvio S.

Reputation: 547

HelloWorld example returns a syntax error on React

I tried to check all the libraries/packages that I needed to run a simple example of HelloWorld on React.js without success.

var React = require('react');
var ReactDOM = require('react-dom');

ReactDOM.render(
    <h1>Hello, world!</h1>,
    document.getElementById('example')
);

The error is the following:

/Users/Silvio/WebstormProjects/untitled/main.js:5
    <h1>Hello, world!</h1>,
    ^

SyntaxError: Unexpected token <

I have installed babel and ReactDOM.

Upvotes: 0

Views: 780

Answers (3)

csm
csm

Reputation: 718

The code itself is correct, but you probably aren't running it properly as it is meant to be run in the browser, not in Node.js. If require is used to import dependencies, main.js must first be processed by a bundler like webpack before it is ready for use.

The following snippet is essentially the same code that you have posted but the dependencies (React and ReactDOM) are imported via script tags.

ReactDOM.render(<h1>Hello, world</h1>, document.getElementById("example"))
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello, world</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.4.2/react-dom.js"></script>
  </head>
  <body>
    <div id="example"></div>
  </body>
</html>

Here Babel, which transpiles JSX (<h1>Hello, world</h1>) is provided by the snippet editor. This minimal example imports Babel as a dependency and transpiles the JSX portion at run time.

Upvotes: 0

Shubham Khatri
Shubham Khatri

Reputation: 281894

In your .babelrc file you need to specify the following

  { 
    "presets": ["react", "stage-0", "es2015"] 
  }

Also you need to install the above presets like

npm install -S babel-preset-react babel-preset-stage-0 babel-preset-es2015

Along with that you webpack.config.js must look something like below to enable babel for .js or .jsx file extensions

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: './main.js',
  output: { path: __dirname, filename: 'bundle.js' },
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,

      }
    ]
  },
};

You can refer here and here for more details

Upvotes: 1

flexicious.com
flexicious.com

Reputation: 1671

You need to run this through babel first - with react and stage-0 presets enabled.

We do this for our sample code here:

https://github.com/flexicious/react-redux-datagrid

Upvotes: 0

Related Questions