Fix - Module not found: Can't resolve 'react-router-dom'
In this tutorial, we are going to learn about how to fix the cannot find module ‘react-router-dom’ error in React.js app.
This error occurs due to the following reasons:
-
The ‘react-router-dom’ package is not installed in the correct project directory.
-
Using the package without installing it in the project.
-
Installed the ‘react-router-dom module’ in a global context and trying to access it in the project local context.
To fix the error “Module not found: Can’t resolve ‘react-router-dom’”, open the project root folder in your terminal and run the following command to install the react-router-dom
package and restart the development server.
npm install react-router-dom
# For TypeScript types use the below command
npm install --save-dev @types/react-router-dom
If you want to install a particular version of ‘react-router-dom’ package use the following command.
npm install react-router-dom@6.0.8
This above command will also add the react-router-dom package to the dependencies list inside a package.json file.
Now, you can use the react-router-dom package in your React.js app.
If you’re still facing the error, then follow the below steps to resolve it.
- Remove the
node_modules
folder andpackage-lock.json
file, inside your project directory by using the below command.
rm-rf node_modules package-lock.json
or you can remove it manually by right-clicking on it and selecting the delete
option.
- Clear the npm cache.
npm clean cache --force
- Re-install the node modules again by running the
npm install
command.
Verify now if you’ve installed it correctly or not by opening the package.json
file and check for react-router-dom
package in the dependencies
object.
"dependencies": {
//...
"react-router-dom": "^6.0.8",
//.. other packages
}
Conclusion
The Cannot find module ‘react-router-dom’ error occurs, if you’re trying to access a react-router-dom
package that is currently not installed in your project. To solve the error, open the project root folder in your terminal and install the react-router-dom
module using the
npm install react-router-dom
command.