skip to Main Content

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


  1. Each <Route> should be a direct child of <Routes>.


    Change your main to:

    ReactDOM.createRoot(document.getElementById('root')).render(
      <React.StrictMode>
          <App/>
      </React.StrictMode>
    )
    

    And then defined all your <Routes> and <Route> in App:

    function App() {
      return (
        <Routes>
         <Route path="/" exact component={Home}/>
        </Routes>
      )
    }
    
    Login or Signup to reply.
  2. React router dom the API recieved some changes
    You need to change router in your main to browser router:

    import React from 'react';
    import ReactDOM from 'react-dom/client';
    import App from './App';
    import './index.css';
    import { BrowserRouter as Router } from 'react-router-dom';
    
    ReactDOM.createRoot(document.getElementById('root')).render(
      <React.StrictMode>
        <Router>
          <App/>
        </Router>
      </React.StrictMode>
    );
    

    than in your app.jsx you also need to change component prop to element and pass JSX directly

    import { Route, Routes } from "react-router-dom";
    import Home from "./Pages/Home";
    
    function App() {
      return (
        <Routes>
          <Route path="/" element={<Home/>} />
        </Routes>
      );
    }
    
    export default App;
    

    This should fix the Uncaught TypeError

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search