I have a component SampleComponent.tsx:
import React from 'react';
type Props = { text: string };
export const SampleComponent: React.FC<Props> = ({text})=><div>{text}</div>;
SampleComponent.variant1 = ({text})=><div>{'variant1' + text}</div>;
When I try using SampleComponent.variant1 in other components, I get typescript error:
Property 'variant1' does not exist on type ...
Right now I am just casting type with as, but I think there is a better way.
How can I fix this?
Edit: How to type if I have dynamic variants - from 1 to 4 such - .variant1, .variant2, .variant3 and .variant4
Since you've said that Sample Component is an FC, react won't let you add any properties that aren't a part of FC. You can either expand the type you declare SampleComponent as, something like this:
export const SampleComponent: React.FC<Props> & {
variant1: React.FC;
} = ({ text }) => <div>{text}</div>;
SampleComponent.variant1 = ({ text }) => <div>{"variant1" + text}</div>;
Or you can provide the type for the props but then let typescript figure out the rest by the way you use it:
const SampleComponent = ({ text }: Props) => <div>{text}</div>;
SampleComponent.variant1 = ({ text }: Props) => <div>{"variant1" + text}</div>;