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!!
The React. js error "X is not defined react/jsx-no-undef" occurs when we forget to import a function, class or a variable in our code before using it. To solve the error, make sure to import the value before using it in your code, e.g. import {myFunc} from 'my-package' .
To check which React version is your project using you need to open the package. json. Take a look under the dependencies section. It should list all of the dependencies of your project and one of those should be React.
Components are independent and reusable bits of code. They serve the same purpose as JavaScript functions, but work in isolation and return HTML. Components come in two types, Class components and Function components, in this tutorial we will concentrate on Function components.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With