I am creating application in react using router below is my code
main.jsx
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import { Router} from 'react-router-dom'
ReactDOM.createRoot(document.getElementById('root')).render(
<React.StrictMode>
<Router>
<App/>
</Router>
</React.StrictMode>
)
app.jsx
import { Route } from "react-router-dom"
import Home from "./Pages/Home"
function App() {
return (
<>
<Route path="/" exact component={Home}/>
</>
)
}
export default App
home.jsx
import Header from "../Components/Header/Header";
function Home() {
return <><Header/></>
}
export default Home;
dependencies:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-router-dom": "^6.22.3"
},
"devDependencies": {
"@types/react": "^18.2.64",
"@types/react-dom": "^18.2.21",
"@vitejs/plugin-react": "^4.2.1",
"eslint": "^8.57.0",
"eslint-plugin-react": "^7.34.0",
"eslint-plugin-react-hooks": "^4.6.0",
"eslint-plugin-react-refresh": "^0.4.5",
"vite": "^5.1.6"
}
And I am getting error as
Uncaught TypeError: Cannot read property ‘pathname’ of undefined at new Router
why am i getting this error
2
Answers
Each
<Route>
should be a direct child of<Routes>
.Change your main to:
And then defined all your
<Routes>
and<Route>
inApp
:React router dom the API recieved some changes
You need to change router in your main to browser router:
than in your app.jsx you also need to change component prop to element and pass JSX directly
This should fix the Uncaught TypeError