Home > other >  What type to give to a component passed in props in a child component?
What type to give to a component passed in props in a child component?

Time:07-29

Assuming i have this written in App.tsx :

<Layout 
    header={ <Header/> }
</layout>

and the Layout component :

export default function Layout({header, body}: any) {
return (
    <div className="layout">
        {header}
        {body}
    </div>
);

}

My props are typed as 'any' because i didnt found another way to type these props components.

Can you give me how to determine the type in my example ?

Thank you

CodePudding user response:

I think you're looking for ReactNode:

type LayoutProps = {
  header: ReactNode;
  body: ReactNode;
}

export default function Layout(props: LayoutProps) {
  return (
    <div >
      {props.header}
      {props.body}
    </div>
  );
}

CodePudding user response:

try this:

export interface ILayoutProps  {
   header: React.FC;
   body: React.FC;
}

export default function Layout({header, body}: ILayoutProps) {
return (
  <div className="layout">
     {header}
     {body}
  </div>
);

notice! you should use the exact same React.FC type for your components.

CodePudding user response:

You can use this:

export default function Layout({header, body}: {header: ReactNode, body: ReactNode}) {
return (
  <div className="layout">
     {header}
     {body}
  </div>
);

OR you can breakdown propTypes as:

export interface IComponentProps {
   header: ReactNode;
   body: ReactNode;
}

{header, body}: IComponentProps
  • Related