enzou
enzou

Reputation: 316

How to typing renderItem Flatlist received by prop in react native and TS?

I have a component HorizontalList that render this:

<HorizontalList
  data={categories}
  renderItem={renderCategories}
  titleList={'Categories'}
/>

enter image description here

this is my component file that receives the following props

//HorizontalList.tsx

interface Props {
  titleList: string;
  data: object[];
  renderItem: <--- //IDK what type should be here;
}

const HorizontalList: React.FC<Props> = ({titleList, data, renderItem}) => {
  return (
    <View style={styles.root}>
      <Text style={styles.titleText}>{titleList}</Text>
      <FlatList horizontal data={data} renderItem={renderItem} />
    </View>
  );
};

but I dont know what type should be renderItem prop, I tried with () => JSX.Element , but in I get the error:

Type '({ item }: { item: ICategorieItem; }) => JSX.Element' is not assignable to type '() => Element'.

Upvotes: 0

Views: 795

Answers (1)

Tarik
Tarik

Reputation: 597

You can do so;

  interface Props {
    titleList: string;
    data: ICategorieItem[];
    renderItem: ({
      item: ICategorieItem,
      index: number,
    }) => React.ReactElement;
  }

or alternatively, you can make use of ListRenderItem from react-native.

For more alternatives, please see this discussion.

    // data prop type definition for FlatList

    data: ReadonlyArray<ItemT> | null | undefined;

    // renderItem prop type definition
    renderItem: ListRenderItem<ItemT> | null | undefined;


When you also see the type defs for renderItem and data props, you will notice that props of those receiving exact same generic type.

Upvotes: 1

Related Questions