Creating a generic component with React TypeScript.

Moatez Bejaoui
eDonec
Published in
3 min readJun 28, 2021

In this topic we will be creating a generic component, so first of all we need to learn what are generic types?

Definition

TypeScript Generics is a tool that provides a way to create reusable components. It creates a component that can work with a variety of data types rather than a single data type. It allows users to consume these components and use their own types. Generics ensures that the program is flexible as well as scalable in the long term.

if you wanna see an example of how to use it check this article that has been written by my colleague and friend bursty who inspired me to write an example about react usage!

So let's get started!

Issue

While working with react, we always map through arrays to display data which is perfectly fine! but what if I told you that we can create a component that can make you stop writing .map in jsx! awesome huh? , so let's start by creating our component!

Solution

First of all, we will be defining what our component will be taking as props!

if you are familiar with react-native you will know that this idea was inspired by FlatList component.

Props :

data: will be our array that will be taking a generic type T!

renderItem: is a function that will be returning a react element of type T as well.

keyExtractor: is a function to extract our key.

Component :

Our GenericList component will be extracting types from the data that will be passed in! , render item will automatically help you with the types because it relies on the data type that will be passed in!

Usage :

Conclusion :

As we saw in this article, using generic components helps us write less, more maintainable, and refactorable code as well it provides a very good experience with IntelliSense integration in the IDE.

Code sandbox :

Q&A

If something doesn’t work as expected or needs more details, just drop a comment below :) Happy coding!

This has been developed by myself at eDonec.

--

--