Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get interface property compomponent props as types

How to define type as props for component. I want to pass component to render inside my component and pass props as object for them with ts types checking.

Thx for help

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

These props need to be generic, because you want to derive one type from the value of another within this type. And the generic parameter needs to be the type of the component, so that it’s props may be inferred.

export interface IWindowProps<Component extends React.FC<any>> {
  ComponentToRender: Component
  ComponentToRenderProps: ComponentProps<Component>
}

And you would use those props with a generic component, so that the generic type parameter may be passed through to the props type.

function MyWindow<Component extends React.FC<any>>(props: IWindowProps<Component>) {
  return <></>
}

Which you would use like so:

function Foo({ abc }: {abc: number}) {
  return <h1>{abc}</h1>
}

// good
const test = <MyWindow ComponentToRender={Foo} ComponentToRenderProps={{ abc: 123 }} />

// error
const bad = <MyWindow ComponentToRender={Foo} ComponentToRenderProps={{ def: 123 }} /> 

Playground


That said, you may be better off with a props that accepts a React.ReactNode instead, so you can render whatever you like in there instead.

For example:

export interface IWindowProps {
  content: ReactNode
}

function MyWindow(props: IWindowProps) {
  return <>{props.content}</>
}

function Foo({ abc }: {abc: number}) {
  return <h1>{abc}</h1>
}

const test = <MyWindow content={<Foo abc={123} />} />

It’s a lot simpler, and it’s more flexible since you don’t need to pass it a true component with props at all, any jsx fragment will do.

Playground

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading