How do I change the color of a single item from a mapped array? My code below will change the color of all the items in the array to green. I want just the item I tap on to turn green. Any help would be appreciated.
import { Text, StyleSheet, View, Pressable } from 'react-native';
import { useState } from 'react';
const PickNotesToTranspose = () => {
const chromaticArrChoose = ['C', 'C#', 'D', 'D#/Eb', 'E', 'F', 'F#/Gb', 'G', 'G#/Ab', 'A', 'A#/Bb', 'B'];
const [isPressed, setIsPressed] = useState(false);
const mapArrChoose = chromaticArrChoose.map((c, index) => {
const handlePress = () => {
isPressed ? setIsPressed(false): setIsPressed(true);
}
return (
<Pressable key={index} onPress={() => handlePress()}>
<Text style={[isPressed? styles.selectedNote: styles.chromatic]}>{c}</Text>
</Pressable>
)
})
return (
<Text>{mapArrChoose}</Text>
)
}
export default PickNotesToTranspose;
const styles = StyleSheet.create({
chromatic: {
fontSize: 32,
},
btnStyle: {
borderWidth: 1,
},
chooseKeyTxt: {
marginTop: 50,
fontSize: 20,
textAlign: 'center',
},
selectedNote: {
color: 'green',
fontSize: 32,
},
})
2
Answers
You should save pressed states in object or array variable.
For example, refer below codes.
Wishing this could help you.
You have created a common sharing state and every item of JSX is pointing or looking the value of pressed at same place.
You can create an state of all item and then use that state to get value of pressed as: