This error occurs when ReactDOM isn’t properly imported or available in your project. Here’s how to resolve it:
Standard Solutions
1. Correct Import Syntax (React 18+)
// For React 18's new root API
import { createRoot } from 'react-dom/client';
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);
2. Legacy Import Syntax (React 17 and below)
import ReactDOM from 'react-dom';
ReactDOM.render(<App />, document.getElementById('root'));
Installation Issues
3. Verify ReactDOM Installation
# Check if react-dom is installed
npm list react-dom
# Install if missing
npm install react-dom
4. Check Version Compatibility
# Verify React and ReactDOM versions match
npm list react react-dom
Should show matching major versions (e.g., both 18.x.x)
Framework-Specific Solutions
5. Next.js Custom _document.js
// pages/_document.js
import { Html, Head, Main, NextScript } from 'next/document';
export default function Document() {
return (
<Html>
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
);
}
6. Gatsby Fix
// gatsby-browser.js
import React from 'react';
import ReactDOM from 'react-dom';
export const replaceHydrateFunction = () => {
return (element, container, callback) => {
ReactDOM.render(element, container, callback);
};
};
Webpack Configuration
7. Ensure Proper Aliasing
// webpack.config.js
module.exports = {
resolve: {
alias: {
'react-dom': path.resolve(__dirname, 'node_modules/react-dom')
}
}
};
Common Mistakes
8. Incorrect Usage in Components
// Wrong: Using ReactDOM in components
function MyComponent() {
// Don't do this!
ReactDOM.render(...);
return <div>...</div>;
}
// Right: Only use at application entry point
9. Multiple React Versions
# Check for duplicate React installations
npm ls react
npm ls react-dom
Testing Environment
10. Jest Configuration
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js']
};
11. Test Setup File
// jest.setup.js
import '@testing-library/jest-dom';
import { configure } from '@testing-library/react';
configure({ testIdAttribute: 'data-test' });
Verification Steps
- Create a test file:
// test-reactdom.js
import ReactDOM from 'react-dom/client';
console.log('ReactDOM available:', !!ReactDOM);
- Check your entry file (typically index.js):
import { createRoot } from 'react-dom/client';
import App from './App';
const root = createRoot(document.getElementById('root'));
root.render(<App />);
Troubleshooting Checklist
- [ ] Verify react-dom is in package.json
- [ ] Check node_modules for react-dom
- [ ] Ensure import statements are correct
- [ ] Confirm no multiple React versions
- [ ] Validate build tool configuration
- [ ] Check framework-specific requirements
- [ ] Test in isolation with minimal example