Home > Enterprise >  React Native FlatList key with multiple rendering
React Native FlatList key with multiple rendering

Time:05-31

I'm trying to render multiple components via FlatList but i get this error : "Warning: Each child in a list should have a unique "key" prop."

I made sure the keyExtractor property was set up correctly but i believe my issue happened when trying to render multiple components inside my FlatList with map.

My FlatList and custom component looks like so :

const ItemView = (row: any) => {
        let title = row.item.title
        let split = title.split(search)
        let searchStringCount = split.length

        return (
            <Text>
                {
                    split.map((elem: string, index: number) => {
                        return (
                            <>
                                <Text style={styles.textListStyle}>
                                    {elem}
                                </Text>
                                {index   1 < searchStringCount &&
                                    <Text style={styles.textHighLightStyle}>
                                        {search}
                                    </Text>}
                            </>
                        )
                    })
                }
            </Text>)
    }


     <FlatList
                style={styles.itemStyle}
                data={filteredData}
                keyExtractor={(item, index) => {
                    return index.toString();
                }}
                ItemSeparatorComponent={ItemSeparatorView}
                renderItem={ItemView} />

I've tried in vain inserting manually a key property to the generated Text components.

CodePudding user response:

you need to add key prop when render with map

          split.map((elem: string, index: number) => {
                    return (
                        <View key={index}>
                            <Text style={styles.textListStyle}>
                                {elem}
                            </Text>
                            {index   1 < searchStringCount &&
                                <Text style={styles.textHighLightStyle}>
                                    {search}
                                </Text>}
                        </View>
                    )
                })
  • Related