skip to Main Content

I am getting the following error when trying to use Typescript with a React Native Flat List:

Type '(item: navigationTypes) => JSX.Element' is not assignable to type 'ListRenderItem<unknown>'.

Here is my code:

type navigationTypes = {
  name: string
  href: string
}

const navigation = [
  { name: 'Support', href: '/support' },
  { name: 'Privacy Policy', href: '/privacy-policy' },
  { name: 'Terms Of Use', href: '/terms-of-use' },
  { name: 'Terms & Conditions', href: '/terms-&-conditions' },
]

  const Item = ({ title = '', href = '' }) => (
    <View>
      <Text>
        <TextLink href={href}>{title}</TextLink>
      </Text>
    </View>
  )

 const renderItem = (item: navigationTypes) => (
    <Item title={item.name} href={item.href} />
  )

       <View>
          <FlatList
            horizontal
            data={navigation}
            renderItem={renderItem}
            keyExtractor={(item) => item.id}
          />
        </View>

I’m new to Typescript so I’m struggling to understand why there is an issue here.

2

Answers


  1. The item is passed as the item property of an object to the renderItem function. Which means that your function signature is not correct.

    If you wrote it inline, it would look like

    renderItem={({ item }) => <Item title={item.name} href={item.href} />}
    

    or

    const renderItem = ({ item }: { item: navigationTypes }) => (
      <Item title={item.name} href={item.href} />
    )
    
    Login or Signup to reply.
  2. const obj = { a: 1, b: 2 };

    const { a, b } = obj;

    const renderItem = {(dataItem.item: navigationTypes) =>

    to avoid this we destructure our object like this.

    {item} = dataItem;

    we are destructuring the items passed to the renderItem function, and navigationTypes is its type.

    const renderItem = {({item}: navigationTypes) =>

    ( <Item title={item.name} href={item.href} /> )}

       <View>
          <FlatList
            horizontal
            data={navigation}
            renderItem={renderItem}
            keyExtractor={(item) => item.id}
          />
        </View>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search