React not defined: ReferenceError: React is not defined

Loading

Solving “React not defined” Reference Error

Why This Error Occurs

The “React not defined” error typically happens when:

  1. React isn’t properly imported in a component file
  2. Using JSX without React in scope (JSX transforms to React.createElement())
  3. Incorrect Babel/TypeScript configuration for JSX processing
  4. Using React 17+ new JSX transform without proper setup

Fixes for Different Scenarios

1. Basic Fix – Add React Import

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

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

2. For React 17+ With New JSX Transform

// No need to import React when using new JSX transform
// But you must configure your compiler (see next section)

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

3. Update Babel Configuration

In your babel.config.js or .babelrc:

{
  "presets": [
    ["@babel/preset-react", {
      "runtime": "automatic" // Enables new JSX transform
    }]
  ]
}

4. Update TypeScript Configuration

In tsconfig.json:

{
  "compilerOptions": {
    "jsx": "react-jsx" // For React 17+ new transform
    // or "jsx": "preserve" if you want to handle transform differently
  }
}

5. For Specific Build Tools

Create React App (already configured)

npx create-react-app@latest my-app

Vite Configuration

// vite.config.js
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react({
    jsxRuntime: 'automatic' // New JSX transform
  })]
})

Common Pitfalls

  1. Forgetting React import in files using JSX
  2. Mixing old and new JSX transforms in a project
  3. Incorrect file extension (.js instead of .jsx for components)
  4. Outdated React scripts version in package.json

Verification Steps

  1. Check all component files have either:
  • import React from 'react' (classic transform), OR
  • Proper JSX transform configuration (new transform)
  1. Verify your build tool is properly configured:
   # Check React version
   npm list react

   # Check Babel plugins
   npm list @babel/preset-react
  1. Ensure consistent JSX handling across your project

Leave a Reply

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