React not defined: ReferenceError: React is not defined

Loading

Fixing “React is not defined” Error in JavaScript/JSX

This error occurs when you’re using JSX syntax but haven’t properly imported React. Here’s how to solve it:

The Root Cause

In JSX files, when you write code like:

const element = <div>Hello</div>;

It gets transformed to:

const element = React.createElement('div', null, 'Hello');

So React must be in scope.

Solutions

1. Import React (Required for React 17 and below)

import React from 'react'; // Add this at the top of your file

function Component() {
  return <div>Hello World</div>;
}

2. For React 18+ with New JSX Transform

If using React 18+ with updated tooling:

  1. First ensure your environment supports the new JSX transform
  2. Then update your ESLint/config if needed
// No need to import React just for JSX in React 18+
function Component() {
  return <div>Hello World</div>;
}

3. Update Babel Configuration

If using custom Babel config, ensure you have:

{
  "presets": [
    "@babel/preset-react",
    "@babel/preset-env"
  ]
}

4. Check Your Build Tools

For Create React App (v4+), Next.js (v11+), or Vite – they support the new JSX transform automatically.

Common Fixes by Environment

Create React App

npx create-react-app@latest my-app
cd my-app
npm start

Next.js

npx create-next-app@latest

Vite

npm create vite@latest my-app --template react
cd my-app
npm install
npm run dev

Additional Checks

  1. Verify React is installed:
   npm list react
  1. Check your package.json has correct versions:
   "dependencies": {
     "react": "^18.2.0",
     "react-dom": "^18.2.0"
   }
  1. If using TypeScript, ensure tsconfig.json has:
   {
     "compilerOptions": {
       "jsx": "react-jsx"
     }
   }

When Using CDN (Not Recommended for Production)

<script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

Leave a Reply

Your email address will not be published. Required fields are marked *