Module not found: Error: Can’t resolve ‘react-dom’

Loading

Solving “Module not found: Error: Can’t resolve ‘react-dom'”

Common Causes of This Error

  1. Missing dependency in your project
  2. Incorrect installation of React packages
  3. Version mismatches between React and ReactDOM
  4. Configuration issues in your bundler (Webpack/Vite)
  5. Corrupted node_modules directory

Step-by-Step Solutions

1. Install React DOM (Basic Fix)

# Using npm
npm install react-dom

# Using yarn
yarn add react-dom

# Using pnpm
pnpm add react-dom

2. Verify Version Compatibility

Ensure your react and react-dom versions match in package.json:

{
  "dependencies": {
    "react": "^18.2.0",
    "react-dom": "^18.2.0"  // Must match major version
  }
}

3. Clean and Reinstall Dependencies

# First remove node_modules and lock files
rm -rf node_modules package-lock.json yarn.lock pnpm-lock.yaml

# Then reinstall
npm install

4. Check Import Statements

Ensure correct imports in your files:

// Client-side rendering (for web)
import ReactDOM from 'react-dom/client';

// Server-side rendering
import ReactDOM from 'react-dom/server';

5. Webpack Configuration (if using)

Add this to your webpack.config.js:

resolve: {
  alias: {
    'react-dom': path.resolve('./node_modules/react-dom')
  }
}

Advanced Troubleshooting

For Create React App Users

# Recreate the entire project if needed
npx create-react-app@latest my-app --template typescript

For Vite Users

# Ensure @vitejs/plugin-react is installed
npm install @vitejs/plugin-react @types/react @types/react-dom

For TypeScript Users

# Install type definitions if missing
npm install --save-dev @types/react @types/react-dom

Version-Specific Solutions

React 18+ Syntax

// New client rendering API
import { createRoot } from 'react-dom/client';

const root = createRoot(document.getElementById('root'));
root.render(<App />);

Legacy React (16-17)

// Older syntax (pre-React 18)
import ReactDOM from 'react-dom';

ReactDOM.render(<App />, document.getElementById('root'));

Prevention Tips:

  • Always install react and react-dom together
  • Use exact version matching in package.json
  • Regularly update dependencies
  • Verify imports when upgrading React versions

Leave a Reply

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