Fixing “React is not defined” Error in Your React Application
This error occurs when you’re trying to use JSX syntax without properly importing React. Here’s how to resolve it and understand why it happens.
Why This Error Occurs
- Missing React Import: JSX gets transformed to
React.createElement()
calls - Incorrect Babel Configuration: JSX transformation not set up properly
- New JSX Transform (React 17+): Different import requirements
Solutions
1. Import React (Traditional Approach – Pre React 17)
// ✅ Add this at the top of your component file
import React from 'react';
function MyComponent() {
return <div>Hello World</div>;
}
2. Using New JSX Transform (React 17+)
If you’re using React 17+ with updated tooling:
- First ensure your Babel config supports the new transform:
// babel.config.json or .babelrc
{
"presets": [
["@babel/preset-react", {
"runtime": "automatic"
}]
]
}
- Then you can write components without importing React:
// ✅ No React import needed with new JSX transform
function MyComponent() {
return <div>Hello World</div>;
}
3. For Create React App Users
Create React App v4+ uses the new JSX transform automatically. Just ensure you have:
// package.json
"dependencies": {
"react": "^17.0.0 || ^18.0.0",
"react-dom": "^17.0.0 || ^18.0.0"
}
Common Fixes for Different Scenarios
1. If Using Webpack
Ensure your webpack config includes:
// webpack.config.js
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-react']
}
}
}
]
}
2. If Using TypeScript
Update your tsconfig.json
:
{
"compilerOptions": {
"jsx": "react-jsx" // or "react-jsxdev" for development
}
}
3. If Using ESLint
Configure your .eslintrc.json
:
{
"rules": {
"react/react-in-jsx-scope": "off" // For new JSX transform
}
}
Verification Steps
- Check React version:
npm list react
- Verify Babel configuration
- Check for syntax errors in your components
Best Practices
- Consistent Imports: Either always import React or use new transform
- Update Tooling: Use current versions of React, Babel, Webpack
- TypeScript Users: Configure jsx properly
- Linting: Set up ESLint to catch missing imports
If You’re Still Seeing the Error
- Clear your cache:
npm start -- --reset-cache
- Check for conflicting React versions:
npm ls react
- Verify your entry point (usually
index.js
) imports React:
import React from 'react';
import ReactDOM from 'react-dom/client';
Remember that since React 17, you have two options:
- Traditional: Import React in every file using JSX
- New JSX Transform: Configure your build tools and don’t import React
Choose one approach and be consistent across your project.