. Advertisement .
..3..
. Advertisement .
..4..
Is the project you’re working on facing this situation “TypeError: Cannot read property ‘location’ of undefined?” You still haven’t found a way to deal with it, even though you have consulted many online tutorials. Are you having a headache because of it? Please continue to follow our article to get the answer!
When does the error “TypeError: Cannot read property ‘location’ of undefined?” occur?
Here is a running program:
useLocation
/Users/hvaandres/Desktop/Development/Ecommerce/modules/hooks.js:29
26 | );
27 | }
28 |
> 29 | return useContext(Context).location;
30 | }
31 |
32 | export function useParams() {
The returned result is reported as follows, no errors occur:
Compiled successfully!
You can now view ecommerce-store in the browser.
Local: http://localhost:3000
On Your Network: http://192.168.1.194:3000
Note that the development build is not optimized.
To create a production build, use npm run build.
However, later this file was not found. Here is a reference guide found to deal with the above problem:
import React from "react";
import invariant from "tiny-invariant";
import Context from "./RouterContext.js";
import HistoryContext from "./HistoryContext.js";
import matchPath from "./matchPath.js";
const useContext = React.useContext;
export function useHistory() {
if (__DEV__) {
invariant(
typeof useContext === "function",
"You must use React >= 16.8 in order to use useHistory()"
);
}
return useContext(HistoryContext);
}
export function useLocation() {
if (__DEV__) {
invariant(
typeof useContext === "function",
"You must use React >= 16.8 in order to use useLocation()"
);
}
return useContext(Context).location;
}
export function useParams() {
if (__DEV__) {
invariant(
typeof useContext === "function",
"You must use React >= 16.8 in order to use useParams()"
);
}
const match = useContext(Context).match;
return match ? match.params : {};
}
export function useRouteMatch(path) {
if (__DEV__) {
invariant(
typeof useContext === "function",
"You must use React >= 16.8 in order to use useRouteMatch()"
);
}
const location = useLocation();
const match = useContext(Context).match;
return path ? matchPath(location.pathname, path) : match;
}
If so, there’s probably something wrong with the “useLocation()” declaration. However the error is still unresolved:
import React, { useState } from 'react';
import { AppBar, Toolbar, IconButton, Badge, MenuItem, Menu, Typography } from '@material-ui/core';
import { ShoppingCart } from '@material-ui/icons';
import { Link, useLocation } from 'react-router-dom';
import logo from '../../assets/logo.png';
import useStyles from './styles';
const PrimarySearchAppBar = ({ totalItems }) => {
const [mobileMoreAnchorEl, setMobileMoreAnchorEl] = useState(null);
const classes = useStyles();
const location = useLocation();
const isMobileMenuOpen = Boolean(mobileMoreAnchorEl);
const handleMobileMenuClose = () => setMobileMoreAnchorEl(null);
const mobileMenuId = 'primary-search-account-menu-mobile';
const renderMobileMenu = (
<Menu anchorEl={mobileMoreAnchorEl} anchorOrigin={{ vertical: 'top', horizontal: 'right' }} id={mobileMenuId} keepMounted transformOrigin={{ vertical: 'top', horizontal: 'right' }} open={isMobileMenuOpen} onClose={handleMobileMenuClose}>
<MenuItem>
<IconButton component={Link} to="/cart" aria-label="Show cart items" color="inherit">
<Badge badgeContent={totalItems} color="secondary">
<ShoppingCart />
</Badge>
</IconButton>
<p>Cart</p>
</MenuItem>
</Menu>
);
return (
<>
<AppBar position="fixed" className={classes.appBar} color="inherit">
<Toolbar>
<Typography component={Link} to="/" variant="h6" className={classes.title} color="inherit">
<img src={logo} alt="commerce.js" height="25px" className={classes.image} /> Commerce.js
</Typography>
<div className={classes.grow} />
{location.pathname === '/' && (
<div className={classes.button}>
<IconButton component={Link} to="/cart" aria-label="Show cart items" color="inherit">
<Badge badgeContent={totalItems} color="secondary">
<ShoppingCart />
</Badge>
</IconButton>
</div>
)}
</Toolbar>
</AppBar>
{renderMobileMenu}
</>
);
};
export default PrimarySearchAppBar;
Solutions for the error “TypeError: Cannot read property ‘location’ of undefined?”
Solution 1: Please readjust as follows
For this situation, you need to keep the following in mind: when you want to use “useLocation()“, then you need to store it in some Router in Router-dom. Please readjust as follows:
in App.js
import { BrowserRouter as Router} from "react-router-dom";
then wrap your components inside Router
<Router>
<Navbar totalItems={cart.total_items}/>
{/* <Products products={products} onAddToCart={handleAddToCart}/> */}
<Cart cart={cart}/>
</Router>
Solution 2: Utilize createBrowserHistory from history
Excepting the solution mentioned above, there is another solution for you to solve the error “TypeError: Cannot read property ‘location’ of undefined?”. Utilizing createBrowserHistory from history will allow you to solve this error. Check out the 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;
This method is very simple, isn’t it? However, it works flawlessly for you. It will make your error completely disappear and your program will run well without any errors. So, what are you waiting without applying it? Let’s try it to get your desired results.
Solution 3: You also can change
To solve this problem, you also can change:
import { Router, Route, Link, browserHistory } from 'react-router';
To:
import { BrowserRouter as Router, Route } from 'react-router-dom';
It will start working. It is due to react-router-dom exports BrowserRouter.
Conclusion
Our above article has given a solution when you encounter the error “TypeError: Cannot read property ‘location’ of undefined?“. We hope you will enjoy this article. If you have any questions, please contact us immediately for support as soon as possible!
Read more
→ Fixing “TypeError: MiniCssExtractPlugin is not a constructor”
Leave a comment