'How to define a generic component and its corresponding configuration?
I'm trying to write a generic component that receive a react component and its config.
My generic component should render the react component and apply its corresponding config prop.
For example:
type AProps = {
name: string;
}
type BProps = {
age: number;
}
type CProps = {
address: string;
}
How can I call MyGenericComp with any component (be it AProps or BProps or CProps) so the config will be enforced?
I tried using generics like so:
type MyGenericComp<T extends (_:any) => JSX.Element> = {
component: T;
config: React.ComponentProps<T>;
}
But it doesn't work quite well because I need to define the generic type and it doesn't work with array of MyGenericComp
Solution 1:[1]
If I understand correctly, you can use this sample code to pass components to CustomeComponent
const AComponent=()=>{
return (<div>A</div>)
}
const BComponent=()=>{
return (<div>B</div>)
}
const CustomeComponent = ({Tag,...rest})=>{
return(
<Tag {...rest} />
);
}
export default function App() {
return (
<div className="App">
<CustomeComponent Tag={AComponent} {...rest}/>
</div>
);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
