TypeError: Cannot read property ‘location’ of undefined – React JS Error Fix
This is one of the common errors caused while doing React routing. This happens when the browser tries to access the history object. You can fix this by adding a history object to routing. The full error is given below.
TypeError: Cannot read property ‘location’ of undefined
Error Fix
You can fix this by using createBrowserHistory from history. Let’s see an example below.
import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { createBrowserHistory } from 'history';
import Login from './login';
import Register from './register';
const Routes = () => {
const history = createBrowserHistory();
return (
<Router history={history}>
<Switch>
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
</Switch>
</Router>
);
}
export default Routes;
There is no explanation as to why this would work and what the problem is. If this was on StackOverflow it would be seized by downvotes.