Categories
TypeScript Answers

How to use generics in props in React in a functional component?

Spread the love

Sometimes, we want to use generics in props in React in a functional component.

In this article, we’ll look at how to use generics in props in React in a functional component.

How to use generics in props in React in a functional component?

To use generics in props in React in a functional component, we can create an interface that takes a generic type and use that as the prop type.

For instance, we write

interface IProps<T> {
  collapsed: boolean;
  listOfData: T[];
  displayData: (data: T, index: number) => React.ReactNode;
}

const CollapsableDataList: React.FunctionComponent<IProps<T>> = (props) => {
  /*...*/
};

to define the IProps<T> type and use T as a type for listOfData and the data parameter of displayData.

Then we use that as the prop type with React.FunctionComponent<IProps<T>> where T is any type that we have already defined.

Conclusion

To use generics in props in React in a functional component, we can create an interface that takes a generic type and use that as the prop type.

Leave a Reply

Your email address will not be published.

If you like the content of this blog, subscribe to my email list to get exclusive articles not available to anyone else.