Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I get 'Unexpected use of 'location' no-restricted-globals'?

In my reactjs code I got:

const {
  children,
  location: { pathname },
} = this.props;

let path = location.pathname;

Also using the react router module in this component. How to fix this error?

like image 492
bier hier Avatar asked Jan 21 '19 03:01

bier hier


2 Answers

In most/all web browsers, location.reload(), for example, is an alias for its fully-qualified name window.location.reload().

You can test it in your browser by opening the dev tools pane console and typing in:

location.reload()

and

window.location.reload()

Both will trigger the page to refresh.

The ES Lint warning is effectively warning you that your code is relying on this alias, so it is plausible that in the future, the code could break suddenly, maybe if the alias became deprecated or some part of your tool chain operated in a manner that required usage of window.

In JavaScript, weird things can happen due to variable-shadowing and closure. It is possible that a location reference could be declared after and then such a reference to something like location.reload() would break with a message such as "no such method reload". This would be less likely to occur if you called the fully-qualified name window.location.reload().

like image 115
agm1984 Avatar answered Sep 20 '22 10:09

agm1984


Because eslint detected location is an element of window. So, try renaming your props:

const {
  children,
  myLocation: { pathname },
} = this.props;

let path = myLocation.pathname;

Reference:

  • https://www.xul.fr/javascript/window-location.php
  • https://eslint.org/docs/rules/no-restricted-globals
like image 27
Hai Pham Avatar answered Sep 17 '22 10:09

Hai Pham