Nikolai
Nikolai

Reputation: 672

'Property does not exist' in a Functional Component with added functional components as properties to it?

I use React with Typescript and a functional approach.

const Divider: React.FunctionComponent<CardDividerProps> = (props: CardDividerProps) => (
   <div>
      divider
   </div>
);

const Card: React.FunctionComponent<CardProps> = (props: CardProps) => (
   <div>
      card
   </div>
);

Card.Divider = Divider; //Property 'Divider' does not exist on type 'FunctionComponent<CardProps>'.

If I remove the explicit type from the Card, it works. But I want to specify it with React.FunctionComponent... Is it possible?

I guess I can create a type:

type CardWithDividerComponent = {
    (props: CardProps): JSX.Element;
    defaultProps: CardProps;
    Divider: React.FunctionComponent<CardDividerProps>;
}

But is this the only solution? Is there any solution with React.FunctionComponent?

Upvotes: 4

Views: 3194

Answers (1)

Drag13
Drag13

Reputation: 5978

You are telling TypeScript that Card is a function with type React.FC. This type doesn't contain any property Divider, so TypeScript complains about that.

To fix the issue, you must tell TypeScript correct type of your component, something like this:

const Card: React.FunctionComponent<CardProps> & {Divider?: React.FunctionComponent<CardDividerProps>} = (props: CardProps) => (
   <div>
      card
   </div>
);

Card.Divider = Divider;

Upvotes: 6

Related Questions