sky_coder123
sky_coder123

Reputation: 2511

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>

Upvotes: 235

Views: 437390

Answers (21)

James
James

Reputation: 196

Update 2025

This worked for me:

import { ProvidePlugin } from 'webpack';
import path from 'path';

export default {
  webpackFinal: async (config) => {
    if (!config.resolve) config.resolve = {};
    if (!config.resolve.alias) config.resolve.alias = {};

    // Define the alias for '@'
    config.resolve.alias = {
      ...config.resolve.alias,
      '@': path.resolve(__dirname, '../src'),
    };

    // Add ProvidePlugin for React
    config.plugins = [
      ...(config.plugins || []),
      new ProvidePlugin({
        React: 'react', // Automatically imports React in every file
      }),
    ];

    return config;
  },
};

Upvotes: 1

Sabbir Ahmed
Sabbir Ahmed

Reputation: 1704

In case you are using CRA and do not want to run eject, then you could install CRACO and put the following settings into craco.config.js file:

export default {
  babel: {
    presets: [
      [
        "@babel/preset-react",
        {
          runtime: "automatic"
        }
      ]
    ]
  }
};

That should remove the Uncaught ReferenceError: React is not defined error.

Upvotes: 4

Jeremy Ashley
Jeremy Ashley

Reputation: 21

import React from 'react'

will work if you're using vite. VS code was telling me that importing react wasn't necessary but maybe that is true for other libraries/build tools but for now if you're using vite import and ignore the error it is giving you.

Upvotes: 2

xdhmoore
xdhmoore

Reputation: 9915

I'm using vite and my config file was

import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";

export default defineConfig({
  plubins: [react()],
  root: "src",
});

I don't know what plubins are or what monkey put them in my config file, but changing it to plugins fixed the problem. PBMAK.

Upvotes: 1

Jkarttunen
Jkarttunen

Reputation: 7631

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"}]
     ]
 }

Upvotes: 326

Viktor
Viktor

Reputation: 398

I got this because I wrote

import react from 'react'

instead of

import React from 'react'

Upvotes: 2

Ifeoluwa Osungade
Ifeoluwa Osungade

Reputation: 305

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

Upvotes: 4

praty
praty

Reputation: 1121

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.

Upvotes: 7

trkaplan
trkaplan

Reputation: 3497

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",

Upvotes: 0

Peter
Peter

Reputation: 1285

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.

Upvotes: 1

pseudosudo
pseudosudo

Reputation: 6600

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

Upvotes: 5

Santosh Suryawanshi
Santosh Suryawanshi

Reputation: 774

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.

Upvotes: 41

anand shukla
anand shukla

Reputation: 706

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

Upvotes: 3

Jephir
Jephir

Reputation: 1441

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

Upvotes: 74

nomad
nomad

Reputation: 1798

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

Upvotes: 2

Rainy
Rainy

Reputation: 11

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

Upvotes: 0

J Santosh
J Santosh

Reputation: 3847

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

Upvotes: 43

Akshat Gupta
Akshat Gupta

Reputation: 2082

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

Upvotes: 126

Abraham Jagadeesh
Abraham Jagadeesh

Reputation: 1957

import React, { Component, PropTypes } from 'react';

This may also work!

Upvotes: 6

Imamudin Naseem
Imamudin Naseem

Reputation: 1702

Adding to Santosh :

You can load React by

import React from 'react'

Upvotes: 19

Barnasaurus Rex
Barnasaurus Rex

Reputation: 1122

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

Upvotes: 109

Related Questions