'Infer props type from React functional component
I am currently using the following mechanism to look up components dynamically:
const COMPONENT_A = "COMPONENT_A";
const COMPONENT_B = "COMPONENT_B";
type ComponentType = typeof COMPONENT_A | typeof COMPONENT_B;
function ComponentA(): JSX.Element {
return <div>Component A</div>;
}
function ComponentB(): JSX.Element {
return <div>Component A</div>;
}
const components: Record<ComponentType, () => JSX.Element> = {
[COMPONENT_A]: () => <ComponentA />,
[COMPONENT_B]: () => <ComponentB />,
};
function OtherComponent(): JSX.Element {
const componentType = COMPONENT_A; //this will come from some external source
const Component = components[componentType];
return <Component />;
}
I'd like to now introduce a props type, such that I can also pass in props to the component. For instance:
interface ComponentAProps {
label: string;
}
function ComponentA({label}: ComponentAProps): JSX.Element {
return <div>{label}</div>;
}
The only solution I have right now is to change my components list to something like:
const components: Record<ComponentType, (props: any) => JSX.Element> = {
[COMPONENT_A]: (props) => <ComponentA {...props}/>,
[COMPONENT_B]: (props) => <ComponentB {...props}/>,
};
Is there a way to infer the props type for each component, such that I don't have use the any type? Ideally, I can define my components to automatically infer the type from the Component itself, so that I can use strong types when I render them in OtherComponent.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
