How can I write a React ponent that takes a React ponent as a prop in typescript?
I want to write code something like this:
const MyComponent = () => (
<span>Hello</span>
);
// this throws "TS2339: Property 'Comp' does not exist on type 'FC{ Comp: FC ; }>'."
const MyComponent2 = ({ Comp = MyComponent }: React.FC<{
Comp: React.ReactNode;
}>) => (
<span>
<Comp />
</span>
);
I do not want to use something like any
or disabling the typescript type checking.
How can I write a React ponent that takes a React ponent as a prop in typescript?
I want to write code something like this:
const MyComponent = () => (
<span>Hello</span>
);
// this throws "TS2339: Property 'Comp' does not exist on type 'FC{ Comp: FC ; }>'."
const MyComponent2 = ({ Comp = MyComponent }: React.FC<{
Comp: React.ReactNode;
}>) => (
<span>
<Comp />
</span>
);
I do not want to use something like any
or disabling the typescript type checking.
2 Answers
Reset to default 2You are confusing props type with variable type. What you have actually done here:
= ({ Comp = MyComponent }: React.FC<{
Comp: React.ReactNode;
}>)
basically you told TS that the props object is a React.FC, which obviously isn't.
So either move the type just right after variable declaration:
const MyComponent2: React.FC<{
Comp: React.ReactNode;
}> = ({ Comp = MyComponent }) => (
or just remove the React.FC
:
const MyComponent2 = ({ Comp = MyComponent }: {
Comp: React.ReactNode;
}) => (
interface Props {
p: JSX.Element // (or React.ReactNode or React.FC, whatever your use case is)
}
const MyComponent: React.FC<Props> = (props) => {}
I don't believe React.FC is the return type of a ponent. It is the type of the function itself.