[React 19] Get context value in class component constructor
I updated version of react from 18.2.0 to 19.1.0 (@types/react to 19.1.6, @types/react-dom to 19.1.5).
After the update I received several components with such errors:
Argument of type 'typeof SplitCostDialog' is not assignable to parameter of type 'ComponentType<never>'.
Type 'typeof SplitCostDialog' is not assignable to type 'ComponentClass<never, any>'.
Target signature provides too few arguments. Expected 2 or more, but got 1.
I found the reason. I use context in class constructor.
export class SplitCostDialog extends React.PureComponent<ISplitCostDialogProps, IState> {
static contextType = ResourcePlanContext;
declare context: IResourcePlanContext;
constructor(props: ISplitCostDialogProps, context: IResourcePlanContext) {
super(props);
const { scope, position } = context.modals.splitPositionCost;
this.state = { form: new SplitCostForm(scope, position) };
}
...
}
How can I use context inside a constructor after updating to version 19? I didn't find the answer in the guide.
Not sure how to type it correctly, but this code will work when you run it (though I think you should pass context to super too with super(props, context). @eps1lon do you know how to fix this type error?
The second argument got lumped in with legacy context way back when
We also need to update docs because it won't work if you don't call super(props, context)
Technically we should require the two-parameter overload if you specify contextType. But that may be hard to ship without breaking existing code.
I'll restore the old behavior in types.
Should be fixed in @types/[email protected]
Thank you very much. I updated to @types/[email protected]. Everything works fine.