I am getting an invalid hook error whenever using anything imported from react-router-dom, such as Router and Route
I got the same invalid hook error when using styled-components, but by re-installing it and forcing it to fix in the command line the error went away. That did not work for this
What should I do to fix it? Do I have duplicate versions of react?
Here is my package.json
{
"name": "my-portfolio",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.16.4",
"@testing-library/react": "^13.3.0",
"@testing-library/user-event": "^13.5.0",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "^2.1.3",
"styled-components": "^5.3.5",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
And here are my npm packages npm list
CodePudding user response:
Delete the package-lock.json and node-modules folder. Then add react-router-dom: "6.3.0" or whatever version you would like to the package.json if it isn't already there.
Restart your IDE and npm install in the terminal
CodePudding user response:
I don't see react-router-dom in your packages.
npm i react-router-dom --force
- If that doesn't work, instead of importing, use require. Like this:
const {BrowserRouter: Router, Routes, Route} = require("react-router-dom")
; Also when you imported Router, did you make sure you wroteBrowserRouter as Router
orBrowserRouter: Router
(for require)?
Because react-router-dom doesn't export Router, it exports BrowserRouter, so if you want to use Router you must say Router as BrowserRouter or the other way for require.