Home > Software engineering >  ERROR Warning: Encountered two children with the same key, `${item}-${index}`
ERROR Warning: Encountered two children with the same key, `${item}-${index}`

Time:05-17

I keep getting this error 'ERROR Warning: Encountered two children with the same key, ${item}-${index}' and don't know why? How can I go about fixing it? Please help thank you in advance!

    return (
        <View style={styles.container}>
            <FlatList 
                data={tabs}
                keyExtractor={(item, index) => '${item}-${index}'}
                renderItem={({ item }) => {
                    return (
                        <TouchableOpacity style={styles.pill} onPress={() => { setSelectedTab(item); }}>
                            <Text style={styles.pillText}>{item}</Text>
                        </TouchableOpacity>
                    )
                }}
            />
    
            <LinearGradient colors={['gold', '#FF7F50', '#FF7F50']} style={StyleSheet.absoluteFill}>
                <Text style={styles.title}>Main Menu Screen</Text>
                <Text style={styles.title}>{ address }</Text>
            </LinearGradient>
        </View>
        );
    };

Error: ERROR Warning: Encountered two children with the same key, ${item}-${index}.

CodePudding user response:

Just replace '' by `` around ${item}-${index} in order to interpolate your variables in the string. But in fact you only need to refer to the index as follows :

return (
        <View style={styles.container}>
            <FlatList 
                data={tabs}
                keyExtractor={(_, index) => index.toString()}
                renderItem={({ item }) => {
                    return (
                        <TouchableOpacity style={styles.pill} onPress={() => { setSelectedTab(item); }}>
                            <Text style={styles.pillText}>{item}</Text>
                        </TouchableOpacity>
                    )
                }}
            />
    
            <LinearGradient colors={['gold', '#FF7F50', '#FF7F50']} style={StyleSheet.absoluteFill}>
                <Text style={styles.title}>Main Menu Screen</Text>
                <Text style={styles.title}>{ address }</Text>
            </LinearGradient>
        </View>
        );
    };
  • Related