Search code examples
javascriptreactjstypescriptreact-props

How to Define ReactNode as a prop for a typescript react component?


How can I write a React component that takes a React component 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.


Solution

  • You 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;
    }) => (