Home > Software engineering >  Flatlist unique "key" pop warning
Flatlist unique "key" pop warning

Time:02-19

With my flatlist I get this message no matter what I try.

Warning: Each child in a list should have a unique "key" prop.

I don't have this issue when my data is a simple array.

const raceClass = <View style={[styles.countdownBoxes, styles.cdown]}>
    <Text style={[styles.titleText, styles.item]}>Race</Text>{timerComponents.length ? timerComponents : <Text>Time's up!</Text>}
</View>;
const deadlineClass = <View style={[styles.countdownBoxes, styles.dline]}>
    <Text style={[styles.titleText, styles.item]}>Deadline</Text>{timerComponentsDeadline.length ? timerComponentsDeadline : <Text>Time's up!</Text>}
</View>;

const flatListItems = [
    { title: "raceCountdown", text: "Race", content: raceClass, styleClasses: "styles.cdown" },
    { title: "deadlineCountdown", text: "Deadline", content: deadlineClass, styleClasses: "styles.dline" }
]
return (
    <View style={styles.timeContainer}>
        <FlatList
        data={flatListItems}
        numColumns={2}
        keyExtractor={(flatListItems) => {flatListItems.title}}
        renderItem={({ item }) => (
            <View style={styles.boxContainer}>
                {item.content}
            </View>
        )} />
    </View>
)

CodePudding user response:

The error is in this line:

keyExtractor={(flatListItems) => {flatListItems.title}}

Because you're using brackets around the function body, you must explicitly return the value. Your function is returning undefined.

With brackets:

keyExtractor={(flatListItems) => {return flatListItems.title}}

Without brackets also will work:

keyExtractor={(flatListItems) => flatListItems.title}

See the MDN article on arrow functions here.

This is assuming you can count on title to be unique in your flatListItems, as noted in the comment by Himanshu Patil.

CodePudding user response:

i get that warning fairly often when using flatlists. however, in most cases, it can be safely ignored and doesnt cause any trouble. the keyExtractor prop can actually be removed completely from the flatlist, and it still works fine. However, @Abe 's answer is perfect if you want to fix the problem, but the code runs even now

  • Related