Konrad
Konrad

Reputation: 24661

How to type a component with children prop?

I want to pass a wrapper component as a prop

I tried this:

type HeaderProps = {
  Wrapper: ReactNode;
}

const Header = ({ Wrapper }: HeaderProps) => {
  return (
    <Wrapper>
      <button>click me</button>
    </Wrapper>
  )
}

But it results in an error:

JSX element type 'Wrapper' does not have any construct or call signatures.

Example wrapper component:

type SomeWrapperProps = {
  children: ReactNode;
}

const SomeWrapper = ({ children }: SomeWrapperProps) => {
  return (
    <div>
      {children}
    </div>
  )
}

Usage:

<Header Wrapper={SomeWrapper} />

or

<Header Wrapper={(props) => <SomeWrapper {...props} other={props} />} />

What should I replace ReactNode with to make it work?

Is there any other syntax to make things work like that?

Upvotes: 1

Views: 93

Answers (1)

kind user
kind user

Reputation: 41893

I'd choose FC type. You could also pass your custom props to it if SomeWrapper accepts more props than children.

type HeaderProps<T = {}> = {
  Wrapper: FC<T>;
};

const Header = ({ Wrapper }: HeaderProps<CustomProps>) => {
  return (
    <Wrapper>
      <button>click me</button>
    </Wrapper>
  );
};

Upvotes: 3

Related Questions