Reputation: 63
TypeError: Cannot read properties of undefined (reading 'pathname')
What is the problem? My code
import {BrowserRouter as Routes, Route, Router} from "react-router-dom";
const App = () => {
return (
<div className={stl.container}>
<Header/>
<Nav/>
<Router>
<Routes>
<Route path='/messages' element={<Messages/>}/>
<Route path='/profile' element={<ProfileContent/>}/>
</Routes>
</Router>
</div>
);
}
Upvotes: 6
Views: 8141
Reputation: 1
import is in wrong way,
import like this
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom'
correct sequence is Router then Routes then Route You are importing Routes Route Router :)
Upvotes: 0
Reputation: 1
Must Use Attribute (to="#") with Link and see that this will run
Upvotes: 0
Reputation: 11
Remove "/" from the beginning of the path attribute in Route component. Ex: <Route path='messages' element={}/>. Also give the same value to the "to" attribute in Link Component Ex: Messages
Upvotes: 0
Reputation: 141
The issue is due to you cannot pass an 'undefined' or 'null' value to the attribute, like in my case, I could have added a null-check, but I chose to add a "/" before it, as shown
Upvotes: 0
Reputation: 203333
Fix the imports. You're importing BrowserRouter
as Routes
.
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
Move the Nav
component into the Router so it has a routing context provided to it. Any Link
components rendered need the routing context.
const App = () => {
return (
<div className={stl.container}>
<Router>
<Header/>
<Nav/>
<Routes>
<Route path='/messages' element={<Messages/>} />
<Route path='/profile' element={<ProfileContent/>} />
</Routes>
</Router>
</div>
);
}
If the code still isn't working then check your installed version of react-router-dom
from your project's directory run:
npm list react-router-dom
If it is any v6.x version then you should be good. If there's still issue though then I suggest uninstalling and reinstalling react-router-dom
.
npm un -s react-router-dom
npm i -s react-router-dom
then run the list command above to validate/verify the installed version.
Upvotes: 1
Reputation: 520
Maybe something is wrong with your environment. I had the same issue, reinstalling packages really helped me.
Upvotes: 1