Solving “React not defined” Reference Error
Why This Error Occurs
The “React not defined” error typically happens when:
- React isn’t properly imported in a component file
- Using JSX without React in scope (JSX transforms to
React.createElement()
) - Incorrect Babel/TypeScript configuration for JSX processing
- 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
- Forgetting React import in files using JSX
- Mixing old and new JSX transforms in a project
- Incorrect file extension (.js instead of .jsx for components)
- Outdated React scripts version in package.json
Verification Steps
- Check all component files have either:
import React from 'react'
(classic transform), OR- Proper JSX transform configuration (new transform)
- Verify your build tool is properly configured:
# Check React version
npm list react
# Check Babel plugins
npm list @babel/preset-react
- Ensure consistent JSX handling across your project