javascriptreact-nativetouchableopacity

How can I add unique keys to <TouchableOpacity> components in React Native?


I am trying to generate unique keys for some <TouchableOpacity> components that I would like to pass in onPress but it's not picking up the key variable.

const options = ["pic1","pic2","pic2"];

export default function ColourScreen() {
    
    const handlePress = (key) => {
       ...do something wity key...
    }

    return (
        
        <View>

            <TouchableOpacity onPress={key => handlePress(key)}>
                <Image
                    style={styles.icon}
                    source={require('../../../assets/icons/icon_1.jpg')}
                />
            </TouchableOpacity>

            <TouchableOpacity onPress={key => handlePress(key)}>
                <Image
                    style={styles.icon}
                    source={require('../../../assets/icons/icon_2.jpg')}
                />
            </TouchableOpacity>

            <TouchableOpacity onPress={key => handlePress(key)}>
                <Image
                    style={styles.icon}
                    source={require('../../../assets/icons/icon_3.jpg')}
                />
            </TouchableOpacity>

        </View>

    )
}

I've tried manually setting it like:

<TouchableOpacity 
    key = {1}
    onPress={key => handlePress(key)}>
    <Image
        style={styles.icon}
        source={require('../../../assets/icons/icon_1.jpg')}
    />
</TouchableOpacity>

or:

{options.map((option, key) =>
    <TouchableOpacity
        key = {key}
        onPress={() => handlePress(key)}>
    <Image
        style={styles.icon}
        source={require('../../../assets/icons/icon_1.jpg')}
     />
    </TouchableOpacity>, ...

)}

But this just creates multiple components.

How can I successfully do this?


Solution

  • You could take the key and map it to your icon.

    const icons = [
      require(`../../../assets/icons/icon_1.jpg`),
      reqiuire(`../../../assets/icons/icon_2.jpg`),
      require(`../../../assets/icons/icon_3.jpg`),
      require(`../../../assets/icons/icon_4.jpg`),
    ]
    
    {options.map((option, key) =>
        <TouchableOpacity
            key = {key}
            onPress={() => handlePress(key)}>
        <Image
            style={styles.icon}
            source={icons[key]}
         />
        </TouchableOpacity>
    )}