0

I expect useEffect to console log but the project fails to compile and gives an error in terminal Unexpected use of 'location' no-restricted-globals I dont have to use the useEffect would be happy if I can get a function to fire each time the location changes

import React, { useState, useEffect } from 'react';
import { BrowserRouter, Switch, Route } from 'react-router-dom';
import { CSSTransition, TransitionGroup } from 'react-transition-group'
import { Context } from "./components/context";
import { Layout } from "./components/layout";
import { Home } from './routes/home';
import { NotFound } from './routes/not-found';

const Router: React.FC = () => {

  useEffect(() => {
    console.log('location changed')
  }, [location]);

  return (
    <Context.Provider value={{ global, setGlobal }}>
      <BrowserRouter>
        <Route render={({location}) => ( //<-------- this is the location!!!
          <Layout>
            <TransitionGroup>
              <CSSTransition timeout={450} classNames='fade' key={location.key}>
                <Switch location={location}>
                  <Route exact path = '/' component = {Home} />
                  <Route exact path = '/my/profile/' component = {Home} />
                  <Route component = {NotFound}/>
                </Switch>
              </CSSTransition>
            </TransitionGroup>
          </Layout>
        )} />
      </BrowserRouter>
    </Context.Provider>
  );
}

export { Router };
Bill
  • 4,614
  • 13
  • 77
  • 132
  • Possible duplicate of [How to detect route changes with react-router v4?](https://stackoverflow.com/questions/51459919/how-to-detect-route-changes-with-react-router-v4) – Agney Sep 22 '19 at 12:40
  • That question is not specific to typescript or functional components as such the responses are all showing answers in class based components – Bill Sep 22 '19 at 12:50

1 Answers1

0

The error is self-descriptive. You did not declare the variable name location anywhere. If it is a global variable, you need to declare it like so:

Filename: global.d.ts
declare var location: type
Matthew Barbara
  • 3,792
  • 2
  • 21
  • 32