I am trying to implement a compound design pattern. For this, I have to pass a react component as a property to another react component.
Here is the code:
function FlyOut(props) {
return (
<div>
{props.children}
</div>
);
}
function Toggle() {
return (
<div>
<Icon />
</div>
);
}
FlyOut.Toggle = Toggle;
Since I am using typescript I will have to specify types to these components.
Without this statement: FlyOut.Toggle = Toggle;
. I specified the typescript types as follows:
type FlyoutProp={
children?: ReactNode | undefined;
}
function FlyOut=React.FC<FlyoutProp>(props)=> {
return (
<div>
{props.children}
</div>
);
}
function Toggle:React.FC<void> =()=> {
return (
<div>
<Icon />
</div>
);
}
Now that I add this statement FlyOut.Toggle = Toggle;
I tried this:
type FlyoutProps = {
children?: ReactNode | undefined;
};
type ExtendedReactFC = React.FC<FlyoutProps> & {
Toggle?: ReactNode | undefined;
};
function FlyOut=ExtendedReactFC<FlyoutProp>(props)=> {
return (
<div>
{props.children}
</div>
);
}
function Toggle:React.FC<void> =()=> {
return (
<div>
<Icon />
</div>
);
}
FlyOut.Toggle = Toggle;
But this did not work. Please can anyone guide me/
CodePudding user response:
You need to change ExtendedReactFC<FlyoutProp>
to ExtendedReactFC
because ExtendedReactFC
doesn't accept generic type
type FlyoutProps = {
children?: ReactNode | undefined;
};
type ExtendedReactFC = React.FC<FlyoutProps> & {
Toggle?: ReactNode | undefined;
};
function FlyOut=ExtendedReactFC(props)=> {
return (
<div>
{props.children}
</div>
);
}
If you want to make it accept generic type props you can change it to
type FlyoutProps = {
children?: ReactNode | undefined;
};
type ExtendedReactFC<T extends Record<string,any>> = React.FC<T> & {
Toggle?: ReactNode | undefined;
};
function FlyOut=ExtendedReactFC<FlyoutProps>(props)=> {
return (
<div>
{props.children}
</div>
);
}