#Using Generics in a compound component

1 messages · Page 1 of 1 (latest)

crude flax
#

Hello, I'm building a compound React component (e.g. Table, Table.Row, Table.Cell). The parent component (e.g. Table) has a config prop that should infer the type of the provided configuration. However, I'm having trouble making this work.

Here's the call site

// call-site.tsx

<Table options={myOptions}>
  <Table.Row>...</Table.Row>
</Table>

and here's the compound table component that needs Options as a generic

// table.tsx

type TableProps<Options extends {}> = {
  // table parent props
}

??? how can TableProps accept a generic from the call site ???

type TableComponent = FC<TableProps> & {
  Row: typeof CollectionFilters
}

??? how can TableComponent accept a generic from the call site ???
                      
export const Table: TableComponent = ({
  options,
  children,
}) => (
  <TableProvider options={options}>
    {children}
  </TableProvider>
)

Table.Row = TableRow

Is it possible to use generics in a compound component like this?

sour flower
#

@crude flax Short answer is "no", React components really can't infer/know anything about the structure of their children at a type level.

#

At a type level, all children are just JSX.Element.

crude flax
#

thanks @sour flower , I suspected that but was hoping I was missing something.

sour flower
#

You can make a 'wrapper' component that ties them together with a generic, but that ends up being less flexible, generally.

#

Some sort of generic hook approach that returns JSX that can be flexibly 'arranged' to the users needs can work, too.

crude flax
#

Could you point me towards a wrapper pattern like this?