Search code examples
javascripttypescriptreact-nativetypesinterface

Typescript: Assign prop type to component prop in a custom component in React Native


I am creating a custom reusable component which can take in another Component as a prop to used as a children. I want to add the type dynamically form the data which is passed into this component.

The best reference is <FlatList>. I need exactly how <FlatList> is created. We have a renderItem prop for it where it will take in that component and pass the data's type to the renderItem function.

Example:

<FlatList
    data={['str1', 'str2', 'str3']} // Array type is string[] here
    renderItem={({item}) => <Text>{item}</Text>} // The item type is string here />

Desired Component:

<MyComponent
    data={[ { name: 'abc', age: 5 }, { name: 'xyz', age: 5 } ]} // Array is a custom type User[]
    renderItem={({item}) => <Text>{item.name}</Text>} /> // The item is User type 

Solution

  • FlatList is using generic parameters to achieve the desired result. You can create a custom component that using the same mechanism. Here's an example:

    type MyComponentProps<T> = {
        data: T[]
        renderItem: (item: T) => React.ReactNode
    }
    
    const MyComponent = <T,>({data, renderItem}: MyComponentProps<T>) => {
        // you code 
    }
    

    Hope it's helps