Skip to content
Advertisement

Getting undefined is not an object when using react-native’s FlatList

Recently began to study React Native. Now I try to display an array of objects on the page. I did everything as if right, but I get an error:

Undefined is not an object (evaluating 'task.name'

I have two questions, what am I doing wrong and why in React Native, elements are displayed using FlatList and not via the map method? Here is my code snippet:

import React, { useState } from "react";
import { FlatList, StyleSheet, Text, View } from "react-native";

export default function Tasks() {
  const [tasks, setTasks] = useState([
    { id: 1, name: "By Bread" },
    { id: 2, name: "By pizza" },
    { id: 3, name: "By snack" },
  ]);

  return (
    <View>
      <FlatList data={tasks} renderItem={({ task }) => <Text key={id}>{task.name}</Text>} />
    </View>
  );
}

const styles = StyleSheet.create({});

Advertisement

Answer

Use item instead of task because renderItem gets as parameter an object with item holding the current row from data array. Like so:

import { useState } from "react";
import { FlatList, StyleSheet, Text, View } from "react-native";

export default function Tasks() {
  const [tasks, setTasks] = useState([
    { id: 1, name: "By Bread" },
    { id: 2, name: "By pizza" },
    { id: 3, name: "By snack" },
  ]);

  return (
    <View>
      <FlatList
        data={tasks}
        keyExtractor={(item) => item.id}
        renderItem={({ item }) => <Text>{item.name}</Text>}
      />
    </View>
  );
}

Here is renderItem‘s destructed signature from the official doc:

renderItem({ item, index, separators });

Also you have a key = {id} on Text that you don’t need.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement