2

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 <></>;
}
3
  • AppTable doesnot return React.FC , it is React.FC Should be like : AppTable: React.FC<IAppTable<T>> Commented Feb 23, 2021 at 12:14
  • @ShreyGupta so how can i create Generic Functional Component? Commented Feb 23, 2021 at 13:26
  • 1
    Is that what you mean? Take under consideration that AppTable doesn't know the data type so you can't access to its properties. Commented Feb 23, 2021 at 15:07

1 Answer 1

1

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 <></>;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.