My use case is pretty simple, I want to have a dynamic react component and save that in a registry:
import { Component } from 'react';
import DummyComponent from './DummyComponent';
class Registry {
TestComponent: Component = DummyComponent;
}
DummyComponent.tsx:
import { Component } from 'react';
export default class DummyComponent extends Component {
constructor(props: any) {
super(props);
throw new Error('Cannot use this dummy component');
}
}
This is throwing a TypeScript error: ts(2740): Type 'typeof DummyComponent' is missing the following properties from type 'Component<{}, {}, any>': context, setState, forceUpdate, render, and 3 more.
What am I doing wrong? I only want Registry.TestComponent
to be a React component, it does not have to have all those properties since they're not required for a React component.
I made a StackBlitz example to show the error. The error is slightly different, but I believe it to be the same issue.
tsconfig.json
{
"compilerOptions": {
"target": "es2015",
"jsx": "react",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"lib": ["esnext"],
"noEmit": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"strict": true
},
"include": ["src/**/*"]
}
shouldComponentUpdate() Safe to use setState ? Yes! This method is called whenever there is an update in the props or state. This method has arguments called nextProps and nextState can be compared with current props and currentState .
Basic Concepts of setState( )They accept arbitrary inputs (called “props”) and return React elements describing what should appear on the screen. If you need to give the user the opportunity to input something or in some way change the variables the component is receiving as props, you'll need setState .
You can call setState() immediately in componentDidMount() and triggers an extra rendering, but this happens before the browser updates the screen, calling render() twice.
setState() allows you to change state in a React class component. To change the state of a function component, you use the useState() hook. Learn more about it here. setState() enqueues change to the component state and tell React that this component and its children need to be re-rendered with the updated state.
Component
type is an instance of component class, while DummyComponent
is a class itself.
It should be:
class Registry {
TestComponent: ComponentClass = DummyComponent;
}
In case TestComponent
isn't limited to class components, it is:
class Registry {
TestComponent: ComponentType = DummyComponent;
}
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