Gg Wp
Gg Wp

Reputation: 145

Cannot read properties of undefined (reading 'location')

I wrote this code:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { BrowserRouter as Router, Route } from "react-router-dom";
import AboutPage from './pages/aboutPage'

ReactDOM.render(
  <React.StrictMode>
    <Router>
    <Route path='/' component={ App }/>
    <Route path='/about' component={ AboutPage }/>
    </Router>
  </React.StrictMode>,
  document.getElementById('root')
);


Why doesn't it work? I'm getting this error:

How can I fix it? React v17.0.2, React-router v5.2.1, React-router-dom v6.0.1

Upvotes: 8

Views: 32728

Answers (3)

Laurent
Laurent

Reputation: 998

In my case to fix that issue, it was the react-router-dom that wasn't match the react-router package.

For example:

    "react-router": "^5.3.3",
    "react-router-dom": "^5.3.3",
    "@types/react-router-dom": "^5.3.3",

Upvotes: 2

pejman abbaspoor
pejman abbaspoor

Reputation: 41

A Route is only ever to be used as the child of Routes element, never rendered directly. So just wrap your <Route> in a <Routes>

<Router>
  <Routes>
    <Route path='/' component={ App }/>
    <Route path='/about' component={ AboutPage }/>
  </Routes>
</Router>

Upvotes: 4

k-wasilewski
k-wasilewski

Reputation: 4623

Wrap your component (the one where you're using props.location) with the withRouter to inject the former:

import { withRouter } from 'react-router-dom';

class MyComponent extends React.Component {
...
}

export default withRouter(MyComponent);

Upvotes: -1

Related Questions