Home > front end >  how to make generic component in react native?
how to make generic component in react native?

Time:05-27

I want to make a generic component but how can I make it ?

Model:

export interface ISelectOptionsRLV<T, C> {
  data: T[];
  onPress: (option: C[]) => void;
}

GenericComponentList:

import { StyleSheet, Text, View, FlatList } from 'react-native'
import React from 'react'
import { ISelectOptionsRLV } from './Model'

const SelectOptionsRLV = ({ data, onPress }: ISelectOptionsRLV) => {
  return (
    <FlatList
      data={data}
      ...
    />
  )
}

export default SelectOptionsRLV

const styles = StyleSheet.create({})

Now I get this error:

Generic type 'ISelectOptionsRLV<T, C>' requires 2 type argument(s)

I know this error I have to set my types, but then its not generic, I mean I need 4 of my flatlist components and each data type is different. So then I have to make 4 Files, or how I can do it? I want all my data thats come in the component generic so I dont want tocreate 4 Component I want one Flatlist component and use it everytime

CodePudding user response:

Try this:

  • GenericComponentList:
import { StyleSheet, Text, View, FlatList } from 'react-native'
import React from 'react'
import { ISelectOptionsRLV } from './Model'

const SelectOptionsRLV = <T, C>({ data, onPress }: ISelectOptionsRLV<T, C>) => {
  return (
    <FlatList
      data={data}
      ...
    />
  )
}

export default SelectOptionsRLV;

const styles = StyleSheet.create({})

AnotherComponent:

const AnotherComponent = () => {
  return (
    <SelectOptionsRLV<yourType, yourType> data={yourData} onPress={yourFunction} />
  )
}
  • Related