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.