TypeScript - ReactRouter | Arrow function captures the global value of 'this' which implicitly has type 'any'
13,200
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>
)
Author by
Jonca33
Updated on June 16, 2022Comments
-
Jonca33 almost 2 years
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?
-
Jonca33 over 5 yearsThank you so very much, I just lost you on
where State is the type of state field in App.
Right now I'm getting a `cannot find name State' -
adz5A over 5 yearsWhat I meant is that the signature of the Routes component is likely incorrect and should probably be
React.SFC<{ state: AppState }>
as it receives a prop namedstate
which is of same type as thestate
field in theApp
component. Your Game component should also reflect this. While researching this I also stumbled upon a deprecation notice for this signature, following the announcement of thehooks
api probably github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/…. -
Jonca33 over 5 yearsThank you for getting back to me. I'll keep reading on the topic as well.