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'
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?
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>
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With