Categories
React Answers

How to fix “typeerror: cannot read properties of undefined (reading ‘pathname’)” with React Router?

Spread the love

To fix "typeerror: cannot read properties of undefined (reading ‘pathname’)" with React Router, we should wrap the Router component around our app.

For instance, we write

import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";

const Main = () => <h1>Hello world</h1>;

ReactDOM.render(
  <Router>
    <Route path="/" component={Main} />
  </Router>,
  document.getElementById("app")
);

to wrap the Router component around our Route components.

Then we can get the pathname property value using this.props.history.location.pathname property in any component set as the value of the component prop in the Route component.

This is because the Router component injects the history prop into the route components.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *