Creating Reusable React Components with Generics
Learn how to use generics in React functional components to create reusable and type-safe code. This guide covers step-by-step instructions for building flexible components that handle various data types.
Imagine we're working on a React project and we have two components: one for displaying a list of users and another for displaying a list of products. Without using generics, we might end up with creating 2 components with similar code.
The Problem
Duplicating code: Both UserList and ProductList components have almost identical structures.
A better solution is to create a reusable list component that can handle both users and products! Flexibility is key! This is where generics come in handy.
How to Use Generics in React Components
Now, let's dive into how we can use generics to create flexible and reusable components.
First, we'll define a generic component: a List component that can accept an array of any type:
1. Define the Props Interface:
ListProps<T>: an interface that takes a generic typeT.itemsis an array of typeT.renderItemis a builder function that takes an item of typeTand returns a React node. This function allows us to customize how each item is rendered.
2. Define the Generic Component:
List<T>is a component that takes props of typeListProps<T>.- We use the
mapmethod to iterate over theitemsarray and render each item using therenderItemfunction. Note that we will not handle how the item is rendered. - We use the
indexas the key for each list item. For a real-world application, it's better to use a unique identifier if available.
The complete code:
Using the Generic Component
Now that we've defined our generic List component, let's use it with different data types.
Example 1: List of Users
List<User>specifies that theListcomponent will handleUserobjects.- Note that I marked the
Listwith<User>, which is optional. For simplicity, we can just use<List ... />. Typescript will automatically get the type fromitems.
Example 2: List of Products
Similar with example 1, we pass the type and items to List and tell it how to render the items. With this, we can save us a lot of duplicated code.
Conclusion
Generics in React components provide a powerful way to create flexible and type-safe components. By defining a generic component and using it with different data types, we can reduce code duplication and make our codebase easier to maintain!