0
votes

I don't find the way to type a FlatList in react native

export interface Category {
  id: string;
  title: string;
  bg: string;
}
export const CATEGORIES: Category[] = [
  { id: "c1", title: "Italian", bg: "#f5428d" }
];


const Item = ({ data }: { data: Category }) => (
  <View style={styles.item}>
    <Text style={styles.title}>{data.title}</Text>
  </View>
);
const CategoriesScreen = ({ navigation }: CategoriesScreenProps) => {
  const renderItem  = ({
    data,
  }: {
    data: Category;
  }) => <Item data={data} />;
  return (
    <FlatList
      data={CATEGORIES}
      keyExtractor={(item) => item.id}
      renderItem={renderItem}
      numColumns={2}
    ></FlatList>
  );
};

I've got this error in renderItem props:

No overload matches this call. Overload 1 of 2, '(props: FlatListProps | Readonly<FlatListProps>): FlatList', gave the following error. Type '({ data, }: { data: Category; }) => JSX.Element' is not assignable to type 'ListRenderItem'. Types of parameters '__0' and 'info' are incompatible. Property 'data' is missing in type 'ListRenderItemInfo' but required in type '{ data: Category; }'. Overload 2 of 2, '(props: FlatListProps, context: any): FlatList', gave the following error. Type '({ data, }: { data: Category; }) => JSX.Element' is not assignable to type 'ListRenderItem

What's wrong, please?

2
Change data with item - Leri Gogsadze

2 Answers

0
votes

renderItem has the interface ListRenderItem< ItemT > , so the "data" param doesn't exist, because ListRenderItem only knows "item", "index" and "separator". Try to replace its ItemT with your data.

How do you do that? It's simple:

1st - import the ListRenderItem interface from react-native,

import { ListRenderItem } from 'react-native';

2nd - type the constant receiving the renderItem function instead of the params, replacing its "ItemT" with your item interface:

const renderItem: ListRenderItem<Category> = ({ item }) => (
   <Item data={item} />
)

That's it!! Wanna check it out the code? here it is: expo snack

0
votes

I think here the error desribes what went wrond :" Property 'data' is missing in type 'ListRenderItemInfo' but required in type '{ data: Category; }'."

  const renderItem  = ({data}: {data: Category}) => <Item data={data} />

You need to pass an object which has a "data" property, but you did not.

 <FlatList
  data={CATEGORIES}
  keyExtractor={(item) => item.id}
  renderItem= {renderItem} // {(receivesArg)=>renderItem(passArg)}
  numColumns={2}
></FlatList>

or

<FlatList
      data={CATEGORIES}
      keyExtractor={(item) => item.id}
      // import {ReactElement} from "react"
      renderItem= {({ data }:data: Category;}):ReactElement => <Item data={data} />}
      numColumns={2}
    ></FlatList>