简体   繁体   中英

Uncaught ReferenceError: React is not defined

Hi I know this type of question has been asked quite a few times but I couldn't get the answer.

I am trying to write a React hello world example. I have only two files one app.jsx and another homepage.jsx. I am using webpack to bundle the files.

But when I run the code I get Uncaught ReferenceError: React is not defined

My homepage.jsx looks like this

"use strict";

var React = require('react');

var Home = React.createClass({
    render : function() {
        return (
            <div className="jumbotron">                
                <h1> Hello World</h1> 
            </div>
        );
    }
});

module.exports = Home;

My app.js looks like this

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

var Home = require('./components/homePage');

ReactDOM.render(
  <Home/>,
  document.getElementById('app')
);

In browser it throws Uncaught ReferenceError: React is not defined at line 7 ie where I am requiring homepage.

But when I add var React = require('react') in app.jsx it works fine.

I don't understand this. I have included react in homepage.jsx where I am making use of it. In app.jsx I only require react-dom becuase I don't use React. Then why it is giving error in app.jsx.

Pls help!!

Change your app.js to this

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

var Home = require('./components/homePage');

ReactDOM.render(
    <Home/>,
    document.getElementById('app')
);

JSX is transformed into React.createElement() calls, thus React is required in scope. So yes, you are using React in app.js . Get used to import it whenever you use JSX or direct React.* calls.

You can have it without require it in your code.

Add to webpack.config.js :

plugins: [
  new webpack.ProvidePlugin({
    "React": "react",
  }),
],

See https://webpack.js.org/plugins/provide-plugin/#root

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM