Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeScript - ReactRouter | Arrow function captures the global value of 'this' which implicitly has type 'any'

I'm rendering a component via React Router 4 using render={() => </Component />}

I need to pass state to the given component i.e: <Game />

export const Routes: React.SFC<{}> = () => (
  <Switch>
    <Route path="/" exact={true} component={Home} />
    <Route path="/play-game" render={() => <Game {...this.state} />} />
    <Redirect to="/" />
  </Switch>
)

To which TS breaks saying:

The containing arrow function captures the global value of 'this' which implicitly has type 'any' enter image description here

The final goal is to be able to pass the Routes to my main app: i.e:

export default class App extends Component<{}, AppState> {
  public state = {
    // state logic
  }

  public render(): JSX.Element {
      return (
        <BrowserRouter>
          <div className="App">
            <Navigation />
            <Routes />
          </div>
        </BrowserRouter>
      )
  }
}

How could I apply the correct types to suppress this TypeScript error?

like image 907
Jonca33 Avatar asked Jan 14 '19 16:01

Jonca33


1 Answers

Arrow functions do not have lexical contexts, so any invocation of this inside the body of an arrow will degenerate to its value in the outer scope. This is what TS is complaining about.

For your problem of passing the state around you need to pass this as a prop to the Routes component which will dispatch it to the relevant route.

export default class App extends Component<{}, AppState> {
  public state = {
    // state logic
  }

  public render(): JSX.Element {
      return (
        <BrowserRouter>
          <div className="App">
            <Navigation />
            <Routes state={this.state}/>
          </div>
        </BrowserRouter>
      )
  }
}

// you need to pass the correct type to React.SFC<>
// probably something along React.SFC<{ state: State }>
// where State is the type of `state` field in App.
export const Routes: React.SFC<...> = ({ state }) => (
  <Switch>
    <Route path="/" exact={true} component={Home} />
    <Route path="/play-game" render={() => <Game {...state} />} />
    <Redirect to="/" />
  </Switch>
)
like image 191
adz5A Avatar answered Nov 13 '22 11:11

adz5A