Home > other >  How can I resolve this warning ? "Encountered Two Children with the same key, `.$1/.$2`"
How can I resolve this warning ? "Encountered Two Children with the same key, `.$1/.$2`"

Time:12-05

I am making a select input in my react native App using import "react-native-form-select-picker", And the code is working fine still it is giving me a warning as "Encountered Two Children with the same key, `.$1/.$2". So how can I fix this Issue Can someone please help? Below is my lines of code:

import React, { useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, } from 'react-native';
import SelectPicker from 'react-native-form-select-picker';

const options = ["Aadhar Card", "Bank Passbook", "Driving Licence", "Pan Card"];

// create a component
const UpdateDocument = ({ navigation }) => {

    const [selected, setSelected] = useState();

    return (
        <View style={styles.container}>
            <View style={styles.docBox}>
                <SelectPicker
                    placeholder="Select document to Update"
                    style={styles.selectBox}
                    onValueChange={(value) => {
                        // Do anything you want with the value. 
                        // For example, save in state.
                        setSelected(value);
                    }}
                    selected={selected}
                >

                    {Object.values(options).map((val, index) => (
                        <SelectPicker.Item label={val} value={val} key={} />
                    ))}

                </SelectPicker>
            </View>
        </View>
    );
};

// define your styles
const styles = StyleSheet.create({
    container: {
        flex: 1,
        backgroundColor: '#fff',
    },
    docBox: {
        paddingVertical: 10,
        paddingHorizontal: 10,
        borderBottomColor: '#aaa',
        borderBottomWidth: 1,
    },
    selectBox: { borderColor: '#555', borderWidth: 1, borderRadius: 4, }
});

//make this component available to the app
export default UpdateDocument;

CodePudding user response:

Keys help React identify which items have changed, are added, or are removed. That's why React wants you to add unique keys to every element whenever you iterate over a list of objects to render multiple JSX elements. If you omit keys, items do not get stable identities within the list, and React will yell at you in the console: Warning: Each child in a list should have a unique “key” prop.

So if each of your option in the options lst are unique which would only make sense then you can just do this.

{Object.values(options).map((val, index) => (
                        <SelectPicker.Item label={val} value={val} key={val} />
                    ))}
  • Related