Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: React is not defined

I am trying to make ReactJS work with rails using this tutorial. I am getting this error:


Uncaught ReferenceError: React is not defined

But I can access the React object in browser consoleenter image description here
I also added public/dist/turbo-react.min.js as described here and also added //= require components line in application.js as described in this answer to no luck. Additionally,
var React = require('react') gives the error:
Uncaught ReferenceError: require is not defined

Can anyone suggest me on how to resolve this?

[EDIT 1]
Source code for reference:
This is my comments.js.jsx file:

var Comment = React.createClass({   render: function () {     return (       <div className="comment">         <h2 className="commentAuthor">           {this.props.author}         </h2>           {this.props.comment}       </div>       );   } });  var ready = function () {   React.renderComponent(     <Comment author="Richard" comment="This is a comment "/>,     document.getElementById('comments')   ); };  $(document).ready(ready); 

And this is my index.html.erb:

<div id="comments"></div> 
like image 868
sky_coder123 Avatar asked Aug 18 '15 10:08

sky_coder123


People also ask

Is not defined react error?

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' .

Is not defined ReferenceError is not defined?

The most common reason behind the error "Uncaught ReferenceError: $ is not defined" is executing the jQuery code before the jQuery library file has loaded. Therefore make sure that you're executing the jQuery code only after jQuery library file has finished loading.


2 Answers

If you are using Babel and React 17, you might need to add "runtime": "automatic" to config.

 {      "presets": [          "@babel/preset-env",         ["@babel/preset-react", {"runtime": "automatic"}]      ]  } 
like image 129
Jkarttunen Avatar answered Sep 18 '22 12:09

Jkarttunen


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).

like image 28
Barnasaurus Rex Avatar answered Sep 20 '22 12:09

Barnasaurus Rex