Roshni Patel
Roshni Patel

Reputation: 31

Uncaught TypeError: Cannot read properties of undefined (reading 'pathname') : how to solve this router issue?

"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-router-dom": "5.2.0",

This is my App.js file

import React from "react"
import Navbar from "./components/Navbar"
import Main from "./components/Main"
import Details from "./components/Details"

import { BrowserRouter as Switch, Router, Route, Link } from "react-router-dom"


export default function App() {
    return (
        <Router>
            <div className="container">
                <header>
                <ul>
                    <li><Link to="/navbar">Navbar</Link></li>
                    <li><Link to="/main">Home</Link></li>
                    <li><Link to="/details">Details</Link></li>
                </ul>

                <div>
                    <Switch>
                        <Route exact path="/navbar" component={Navbar} />
                        <Route exact path="/main" component={Main}/>
                        <Route exact path="/details" component={Details}/>
                    </Switch>
                </div>
                </header>
            </div>

        </Router>
    )
}

Upvotes: 2

Views: 6164

Answers (1)

Drew Reese
Drew Reese

Reputation: 202667

Just glancing at only the code you've shared, you've mucked up your imports a bit.

import { BrowserRouter as Switch, Router, Route, Link } from "react-router-dom";

You've imported the BrowserRouter as Switch. I'm certain you meant to import it as Router, and to import the Switch separately.

import { BrowserRouter as Router, Switch, Route, Link } from "react-router-dom";

The issue is that you were rendering two routers, and they don't share the routing context they provide. In other words, the "Router" was handling the navigation from the links, but the Route components were getting their routing context from the nested BrowserRouter a.k.a. "Switch".

If this doesn't resolve your issue completely then there may be more relevant code we need to look at. Try the above first though to get your App component into proper working order.

Upvotes: 2

Related Questions