Home > Net >  React Typescript: Extract table to component and pass additional props
React Typescript: Extract table to component and pass additional props

Time:08-01

I want to create custom components for table, td, tr etc in order to style them in one place. How do I specify the props for this? The following code is my attempt to achieve this but I get a lot of errors saying that the props are not assignable to the type.

import React, { ReactNode, FC } from "react";

interface Props {
  children: ReactNode;
}

const Table: FC<Props & HTMLTableElement> = ({ children, ...rest }) => (
  <table {...rest} className="min-w-full divide-y divide-gray-300">
    {children}
  </table>
);

export default Table;

CodePudding user response:

Replace your FC<Props & HTMLTableElement> with:

const Table: FC<
  Props &
    React.DetailedHTMLProps<
      React.TableHTMLAttributes<HTMLTableElement>,
      HTMLTableElement
    >
> = ({ children, ...rest }) => (
  <table {...rest} className="min-w-full divide-y divide-gray-300">
    {children}
  </table>
);

Now you should be able to pass all accepted props of <table />.

  • Related