Search code examples
reactjstypescripttypescript-genericsreact-functional-component

React Typescript Functional Component Syntax Error


I want to create a generic functional component but i get this Error :

Code block ;

interface IAppTable<Type> {
  height: number;
  data: Type[];
  tableLayout: 'auto' | 'fixed';
  pagination?: false;
}

const AppTable: <T>(props: IAppTable<T>) => React.FC<IAppTable<T>> = (props) => {
  const [selectedRows, setSelectedRows] = useState<number[]>([]);
  const getColumns = () => {
    setSelectedRows([1]);
    return [];
  };
  return <></>;
}

Solution

  • As explained by @Shrey, AppTable doesn't return a function component, it is a function component.

    The React.FC type does not support generic components. This isn't a problem because anything that matches the signature of FC can be used as an FC. That signature is that it takes an object of props and returns a JSX.Element. FC automatically includes the children prop, but we can use the helper React.PropsWithChildren to add it ourselves.

    We need to make the function itself generic, so we apply the types to the props and the return rather than to the function itself (which is what React.FC does, and why it cannot work with a generic).

    import React, { useState, PropsWithChildren } from "react";
    
    const AppTable = <T extends any>(props: PropsWithChildren<IAppTable<T>>): JSX.Element => {
      const [selectedRows, setSelectedRows] = useState<number[]>([]);
      const getColumns = () => {
        setSelectedRows([1]);
        return [];
      };
      return <></>;
    }