0

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/

5
  • Why do you do this FlyOut.Toggle = Toggle? Commented Dec 23, 2022 at 15:35
  • For implementing a compound pattern Commented Dec 23, 2022 at 15:37
  • type ExtendedReactFC = React.FC<FlyoutProps> & { Toggle: React.FC<void>; }; Commented Dec 23, 2022 at 15:39
  • Thanks for help but it didn't worked Commented Dec 23, 2022 at 15:49
  • 1
    Can you try to change ExtendedReactFC<FlyoutProp> to ExtendedReactFC Commented Dec 23, 2022 at 15:59

1 Answer 1

1

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>
  );
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.