200

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>
Community
  • 1
  • 1
sky_coder123
  • 2,161
  • 3
  • 14
  • 15

17 Answers17

274

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

In .babelrc config file this would be:

 {
     "presets": [
         "@babel/preset-env",
        ["@babel/preset-react", {"runtime": "automatic"}]
     ]
 }
Jkarttunen
  • 6,764
  • 4
  • 27
  • 29
  • Thanks, this does the job. I'm just wondering why it's better than adding react to `externals` or `plugins` using `ProvidePlugin` in the Webpack config? – Turnip May 19 '22 at 23:15
  • This worked for me. Im using rollup and I had to add this to my plugins: babel({ exclude: 'node_modules/**', presets: [ "@babel/preset-env", ["@babel/preset-react", {"runtime": "automatic"}], ] }), – Herii Jun 16 '22 at 20:38
  • What config? Where should I add it? – mm_ Jan 09 '23 at 16:00
  • Good point! this is was for .babelrc file. – Jkarttunen Jan 10 '23 at 17:16
  • 2
    For those who like more explanation: (credit Chat-GPT): `@babel/preset-react` is a Babel preset that transforms React JSX syntax to plain JS. Adding `{"runtime": "automatic"}` enables a new JSX transform [introduced in React 17] that uses the React runtime to generate necessary code for JSX expressions. This eliminates the need for React to be in scope and allows for better optimisation, [such as generating less code and reducing total bundle size]. The default classic transform requires the `React` object to be in scope. – TheKearnol Apr 24 '23 at 18:06
  • 1
    Also, take note: If you are experiencing this issue after bundling your code with Webpack(4). You likely need to add this option to the `@babel/preset-react` preset listed in the Webpack config file under `loader: "babel-loader"` – TheKearnol Apr 24 '23 at 18:26
113

I got this error because I was using

import ReactDOM from 'react-dom'

without importing react, once I changed it to below:

import React from 'react';
import ReactDOM from 'react-dom';

The error was solved :)

Akshat Gupta
  • 1,904
  • 2
  • 14
  • 13
  • (plus 1) - Makes perfect sense – Paul Samsotha Mar 02 '17 at 08:51
  • 2
    Works! That is a bit unexpected coming from a language like Python. If I'm only using `ReactDOM` in my main file, I thought I can (and should) get rid of the reference to `React`. Oh well, learned something. – jdm May 04 '17 at 23:03
  • with mine React18 I have these imports like:`import React from 'react' import ReactDOM from 'react-dom/client'`, but it doesn't help. – Jack Pts May 23 '23 at 11:31
108

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

Barnasaurus Rex
  • 1,104
  • 1
  • 8
  • 4
64

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

ravibagul91
  • 20,072
  • 5
  • 36
  • 59
Jephir
  • 1,331
  • 17
  • 16
  • 1
    I thought I could do `React: "react"` to be consistent with other `ProvidePlugins`, but no - must be `"React"` quoted. – ecoe Mar 02 '21 at 03:15
  • That worked for me but I had to swap the case `"react":''React"` – Alvin Sep 24 '22 at 11:23
43

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.

  1. If you mention react in externals section inside webpack configuration, then you must load react js files directly into your html before bundle.js
  2. Make sure you have the line import React from 'react';
J Santosh
  • 3,808
  • 2
  • 22
  • 43
39

Try to add:

import React from 'react'
import { render } from 'react-dom'
window.React = React

before the render() function.

This sometimes prevents error to pop-up returning:

React is not defined

Adding React to the window will solve these problems.

xKobalt
  • 1,498
  • 2
  • 13
  • 19
18

Adding to Santosh :

You can load React by

import React from 'react'
Imamudin Naseem
  • 1,604
  • 18
  • 21
  • 1
    @zero_cool I love semi-colons as it makes code easier to read, but they are optional in JavaScript. When omitted, they will be automatically inserted. The official EcmaScript spec has this info: "Moreover, line terminators, although not considered to be tokens, also become part of the stream of input elements and guide the process of automatic semicolon insertion (11.9)." from: https://tc39.github.io/ecma262/#sec-lexical-and-regexp-grammars which points to this: https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion So technically, both of your code examples are correct & valid JS. – Clomp Apr 19 '16 at 17:43
6

I know this question is answered. But since what worked for me isn't exactly in the answers, I'll add it here in the hopes that it will be useful for someone else.

My index.js file looked like this when I was getting Uncaught ReferenceError: React is not defined.

import {render} from 'react-dom';
import App from './App';

render(<App />, document.getElementById("root"));

Adding import React from 'react'; at the top of the file fixed it.

Now my index.js looks like this and I don't get any error on the console.

import React from 'react';
import {render} from 'react-dom';
import App from './App';

render(<App />, document.getElementById("root"));

Please note I made no change in webpack.config.js or anywhere else to make this work.

praty
  • 914
  • 9
  • 11
  • If you are using any React version earlier than 17, then importing React into the file is necessary. 17 and after is supposed to no longer require the React import in files which use JSX – tkd_aj Mar 25 '22 at 09:57
5
import React, { Component, PropTypes } from 'react';

This may also work!

Abraham Jagadeesh
  • 1,757
  • 1
  • 23
  • 21
4

If you're using TypeScript, make sure that your tsconfig.json has "jsx": "react" within "compilerOptions".

pseudosudo
  • 6,270
  • 9
  • 40
  • 53
  • I has the similar: `"jsx": "react-jsx",`, tried your version with simply 'react' - it doesn't help in both cases..( – Jack Pts May 23 '23 at 11:25
3

I was facing the same issue. I resolved it by importing React and ReactDOM like as follows:

import React from 'react';
import ReactDOM from 'react-dom';
xKobalt
  • 1,498
  • 2
  • 13
  • 19
anand shukla
  • 666
  • 5
  • 14
3

I got this error because I used:

import React from 'react';

while working with React, Typescript and Parcel

Changing it to:

import * as React from 'react';

Solved the problem as suggested by https://github.com/parcel-bundler/parcel/issues/1199#issuecomment-381817548

2

I got this error because in my code I misspelled a component definition with lowercase react.createClass instead of uppercase React.createClass.

brooksrelyt
  • 3,925
  • 5
  • 31
  • 54
nomad
  • 1,699
  • 5
  • 21
  • 35
1

Sometimes the order of import can cause this error, if after you have followed all the steps above and still finds it hard on you, try making sure the react import comes first.

import React from 'react'
import { render } from 'react-dom'

before any other important you need to make.

Peter
  • 1,124
  • 14
  • 17
1

I got this because I wrote

import react from 'react'

instead of

import React from 'react'

Viktor
  • 334
  • 1
  • 3
  • 14
0

The displayed error

after that import react

Finally import react-dom

if error is react is not define,please add ==>import React from 'react';

if error is reactDOM is not define,please add ==>import ReactDOM from 'react-dom';

Gowtham
  • 3,198
  • 2
  • 19
  • 30
Rainy
  • 11
  • 1
0

To whom using CRA and ended up to this question, can use customize-cra and react-app-rewired packages to override babel presets in CRA. To do this, create a config-overrides.js in the root and paste this code snippet in it.

const { override, addBabelPreset } = require('customize-cra');

module.exports = override(
    addBabelPreset('@emotion/babel-preset-css-prop'),
    addBabelPreset([
        '@babel/preset-react',
        {
            runtime: 'automatic',
            importSource: '@emotion/react',
        },
    ]),
);

And update scripts in package.json with the ones below.

    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test --env=jsdom",
trkaplan
  • 3,217
  • 2
  • 23
  • 26