I have created a react typescript app with create react app. I now want to have a context which I want accessible across all my components:
export const UserContext = React.createContext<{name: string}>({name: 'Foo'});
The context is linked to the state of the main app component. This state does change and therefore the value of context should also change for the components.
<UserContext.Provider value={this.state}>
<MainPage/>
</UserContext.Provider>
I have followed the doc string suggestion for how to set up in context in a component and so have this:
class MainPage extends React.Component {
static contextType = UserContext;
context!: React.ContextType<typeof UserContext>;
public render() {
return <div>{this.context.name}</div>
}
}
However this.context.name
is always null. I have placed a div with it's value linked to this.state
in the app component and that does show the value unlike the context. I am struggling as the code works when written in raw react / create-react-app and I was under the components where the same in @types/react
?
Does anyone know how to implement context inside a component class in typescript?
Looks like the type parameter of your UserContext
is slightly wrong. You need to remove the typeof
.
so React.createContext<{ name: string }>
instead of React.createContext<typeof { name: string }>
This works for me:
import * as React from 'react';
const UserContext = React.createContext<{ name: string }>({ name: 'test' });
export class MainPage extends React.Component<undefined, undefined> {
static contextType = UserContext;
context!: React.ContextType<typeof UserContext>;
public render() {
return <div>{this.context.name}</div>;
}
}
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