25

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 i.e 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!!

Aniket
  • 4,926
  • 12
  • 41
  • 54

2 Answers2

42

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.

Andreyco
  • 22,476
  • 5
  • 61
  • 65
  • 1
    I'm a bit new to this stuff but any chance you could explain why the `require('react-dom')' does not pull in React? – Doddie Mar 04 '16 at 12:56
  • `react-dom` is only "renderer" which converts React elements into DOM nodes/elements. Take a look at React Native, which does not require `react-dom` since it has its own renderer which converts React elements into native elements depending on platform. In early days, React included code which was extracted into now existing `react-dom`. – Andreyco Mar 04 '16 at 20:14
  • @Andreyco when i use above code, i got this error ReferenceError: require is not defined var React = require('react'); please help me and thanks in advance – mja Oct 13 '16 at 12:01
  • 1
    That looks confusing (the need to import React, despite the code not showing it being used and compiling just fine). Is this the only time where you would need to do something like this? – georaldc Sep 21 '17 at 20:26
14

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

edwardrbaker
  • 753
  • 1
  • 9
  • 20
MiF
  • 638
  • 7
  • 13