I am trying to make ReactJS work with rails using this tutorial. I am getting this error:
Uncaught ReferenceError: React is not defined
If you're using TypeScript, make sure that your tsconfig.json
has "jsx": "react"
within "compilerOptions"
.
If you are using Webpack, you can have it load React when needed without having to explicitly require
it in your code.
Add to webpack.config.js:
plugins: [
new webpack.ProvidePlugin({
"React": "react",
}),
],
See http://webpack.github.io/docs/shimming-modules.html#plugin-provideplugin
If you are using Babel and React 17, you might need to add "runtime2: "automatic" to config.
{
"presets": ["@babel/preset-env", ["@babel/preset-react", {
"runtime": "automatic"
}]]
}
Adding to Santosh :
You can load React by
import React from 'react'
I was able to reproduce this error when I was using webpack to build my javascript with the following chunk in my webpack.config.json
:
externals: {
'react': 'React'
},
This above configuration tells webpack to not resolve require('react')
by loading an npm module, but instead to expect a global variable (i.e. on the window
object) called React
. The solution is to either remove this piece of configuration (so React will be bundled with your javascript) or load the React framework externally before this file is executed (so that window.React
exists).
Possible reasons are 1. you didn't load React.JS into your page, 2. you loaded it after the above script into your page. Solution is load the JS file before the above shown script.
P.S
Possible solutions.
react
in externals section inside webpack configuration, then you must load react js files directly into your html before bundle.js
import React from 'react';