256

I am using React and Redux to develop a webapp and when I started up my project I got this:

Line 13:  Unexpected use of 'location'  no-restricted-globals

Search for the keywords to learn more about each error.

I search a lot about how to resolve it, but none of the answers I found helped me, so I turned to Stack overflow.

Does anyone know how to fix this error? I appreciate all the help I can get.

frogatto
  • 27,475
  • 10
  • 76
  • 119
Martin Nordström
  • 5,219
  • 10
  • 25
  • 59

6 Answers6

610

Try adding window before location (i.e. window.location).

frogatto
  • 27,475
  • 10
  • 76
  • 119
Chasen Bettinger
  • 6,665
  • 1
  • 12
  • 28
  • 1
    Indeed the correct way to fix this is to prefix location with window.location. For some reason, the CRA team currently considers `location` a "confusing browser global". I'd say if you are using CRA and don't know about the location object, you are in no-mans land. Maybe they just want to make reading url annoying, which would be understandable... – Devin Rhode Sep 25 '19 at 12:44
  • I created a github issue specifically asking if the `location` object _really_ is a confusing browser global, therefore needing the `window.` prefix everywhere... https://github.com/facebook/create-react-app/issues/7733 – Devin Rhode Sep 25 '19 at 12:45
13

This is a simple and maybe not the best solution, but it works.

On the line above the line you get your error, paste this:

// eslint-disable-next-line no-restricted-globals

edgar mlowe
  • 151
  • 1
  • 8
Martin Nordström
  • 5,219
  • 10
  • 25
  • 59
4

Use react-router-dom library.

From there, import useLocation hook if you're using functional components:

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

Then append it to a variable:

Const location = useLocation();

You can then use it normally:

location.pathname

P.S: the returned location object has five properties only:

{ hash: "", key: "", pathname: "/" search: "", state: undefined__, }

Marsou001
  • 51
  • 5
0

Perhaps you could try passing location into the component as a prop. Below I use ...otherProps. This is the spread operator, and is valid but unneccessary if you passed in your props explicitly it's just there as a place holder for demonstration purposes. Also, research destructuring to understand where ({ location }) came from.

import React from 'react';
import withRouter from 'react-router-dom';

const MyComponent = ({ location, ...otherProps }) => (whatever you want to render)


export withRouter(MyComponent);
-3

Just destructure locaton like this: ({location}).

shaedrich
  • 4,826
  • 2
  • 26
  • 35
-4
/* eslint no-restricted-globals:0 */

is another alternate approach

Dan Krueger
  • 369
  • 2
  • 10