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?