Design Converter
Education
Last updated on Feb 27, 2025
•5 mins read
Last updated on Feb 27, 2025
•5 mins read
Want to make your React components more flexible without losing type safety?
Generic components can help! They let you build reusable elements that work with different data types while keeping TypeScript’s strict checks in place.
This blog breaks down React generic components with simple examples. You’ll learn how to use generic type parameters, work with various data structures, and apply them in real projects.
Let’s get started!
Generics allow React components to be more flexible while maintaining type safety. Instead of defining a fixed data type, generics enable components to work with different data types. This is achieved using generic type parameters that can be defined when using the component.
• Maintaining Type Safety: Ensures that the props and returned data match expected types.
• Code Reusability: Enables the same component to handle multiple data types.
• Better Type Checking: TypeScript ensures that data passed to the component conforms to its generic type.
• Improved Developer Experience: Reduces type errors and increases predictability.
A generic component can be defined using TypeScript generics. The type parameter <T>
acts as a placeholder for the data type, making the component work with multiple data structures.
The following example shows a React functional component that renders a list of items using a generic type parameter:
1import React from "react"; 2 3interface ListProps<T> { 4 items: T[]; 5 renderItem: (item: T) => JSX.Element; 6} 7 8const ListComponent = <T,>({ items, renderItem }: ListProps<T>) => { 9 return ( 10 <ul> 11 {items.map((item, index) => ( 12 <li key={index}>{renderItem(item)}</li> 13 ))} 14 </ul> 15 ); 16}; 17 18// Usage with strings 19const StringList = () => { 20 const items = ["Apple", "Banana", "Cherry"]; 21 return <ListComponent items={items} renderItem={(item) => <span>{item}</span>} />; 22}; 23 24// Usage with objects 25const ObjectList = () => { 26 const items = [{ id: 1, name: "John" }, { id: 2, name: "Jane" }]; 27 return <ListComponent items={items} renderItem={(item) => <span>{item.name}</span>} />; 28}; 29 30export default ObjectList;
• The generic type parameter <T>
allows the component to handle different data types.
• The ListProps<T>
interface ensures type safety.
• The usage examples demonstrate how TypeScript ensures correct data types.
A React component often requires props to be strongly typed. Using TypeScript generics, we can define a generic component that accepts props of any generic type.
The following example creates a generic component that displays a data card:
1interface CardProps<T> { 2 data: T; 3 renderContent: (data: T) => JSX.Element; 4} 5 6const Card = <T,>({ data, renderContent }: CardProps<T>) => { 7 return <div className="card">{renderContent(data)}</div>; 8}; 9 10// Usage with user objects 11const UserCard = () => { 12 const user = { id: 1, name: "Alice", age: 25 }; 13 return <Card data={user} renderContent={(data) => <p>{data.name} - {data.age}</p>} />; 14}; 15 16export default UserCard;
• Reusability: Works with different data structures.
• Type Safety: Prevents invalid data types.
• Clear Type Checking: TypeScript ensures correct props.
A generic component can be designed to handle different data structures, including arrays, objects, and primitive data types.
This example creates a reusable component for displaying a table.
1interface TableProps<T> { 2 data: T[]; 3 columns: (keyof T)[]; 4} 5 6const Table = <T,>({ data, columns }: TableProps<T>) => { 7 return ( 8 <table> 9 <thead> 10 <tr> 11 {columns.map((col) => ( 12 <th key={col as string}>{col}</th> 13 ))} 14 </tr> 15 </thead> 16 <tbody> 17 {data.map((row, index) => ( 18 <tr key={index}> 19 {columns.map((col) => ( 20 <td key={col as string}>{row[col]}</td> 21 ))} 22 </tr> 23 ))} 24 </tbody> 25 </table> 26 ); 27}; 28 29// Usage with user data 30const UserTable = () => { 31 const users = [ 32 { id: 1, name: "Alice", age: 25 }, 33 { id: 2, name: "Bob", age: 30 }, 34 ]; 35 return <Table data={users} columns={["id", "name", "age"]} />; 36}; 37 38export default UserTable;
• TableProps accepts a generic type for handling different data structures.
• The component ensures type safety using TypeScript generics.
• Works with various data types, including string, number, and objects.
A generic function within a React component ensures maintaining type safety when handling various data types.
1const transformData = <T,>(data: T[], transformFn: (item: T) => string): string[] => { 2 return data.map(transformFn); 3}; 4 5// Usage with numbers 6const numbers = [1, 2, 3]; 7const transformedNumbers = transformData(numbers, (num) => `Number: ${num}`); 8 9console.log(transformedNumbers); // ["Number: 1", "Number: 2", "Number: 3"]
• Maintains type safety when working with generic types.
• Can handle different data structures.
• The arrow function transformFn allows flexible transformations.
Generics work in React Native the same way they do in React. A React Native generic component can ensure type safety while handling different data types.
1import { TouchableOpacity, Text } from "react-native"; 2 3interface ButtonProps<T> { 4 value: T; 5 onPress: (value: T) => void; 6} 7 8const GenericButton = <T,>({ value, onPress }: ButtonProps<T>) => { 9 return ( 10 <TouchableOpacity onPress={() => onPress(value)}> 11 <Text>{String(value)}</Text> 12 </TouchableOpacity> 13 ); 14}; 15 16// Usage with numbers 17<GenericButton value={10} onPress={(num) => console.log(num)} />;
React generic components help developers create flexible and reusable code. They work well with TypeScript to manage different data types while keeping everything structured.
Using generics in React makes it easier to build scalable applications. It improves type-checking and reduces errors. With this approach, developers can write cleaner and more maintainable code.
Tired of manually designing screens, coding on weekends, and technical debt? Let DhiWise handle it for you!
You can build an e-commerce store, healthcare app, portfolio, blogging website, social media or admin panel right away. Use our library of 40+ pre-built free templates to create your first application using DhiWise.