How to change change and track boolean state of each element in an array

Issue

Im trying to make it so that when a TouchableHighlight is pressed in react native it goes from one colour to another. I have state that is set to false and changes when the button is pressed. However this changes the colour for all elements in the map rather than for each item individually. Is there a way to update the state for each element independently?
Here is my code:

function OnboardingVibes() {
  const [pressed, setPressed] = useState(false);
  return (
      <View style={{marginTop: 40}}>
        <Text style={{fontSize: 22, color: '#FFF', marginBottom: 16}}>Vibes</Text>
        <View style={styles.buttonContainer}>
          {vibes.map((vibe) => {
            return (
                <TouchableHighlight onPress={() => setPressed(true)} style={{backgroundColor: pressed ? '#DDD' : '#4D2C5B', margin: 4, borderRadius: 4}} key={`vibe-${vibe}`}>
                  <Text style={styles.vibeButton}>{vibe}</Text>
                </TouchableHighlight>
            )
          })}
        </View>
      </View>
  );
}

Solution

One way to do it is to move the state down so you could have individual states. When the state is true at the top-level, all child components will receive the same state.

function TouchableVibe({vibe}) {
  const [pressed, setPressed] = useState(false);

  return (
    <TouchableHighlight
      onPress={() => setPressed(true)}
      style={{
        backgroundColor: pressed ? "#DDD" : "#4D2C5B",
        margin: 4,
        borderRadius: 4,
      }}
    >
      <Text style={styles.vibeButton}>{vibe}</Text>
    </TouchableHighlight>
  );
}

function OnboardingVibes() {
  return (
    <View style={{ marginTop: 40 }}>
      <Text style={{ fontSize: 22, color: "#FFF", marginBottom: 16 }}>
        Vibes
      </Text>
      <View style={styles.buttonContainer}>
        {vibes.map((vibe) => (
          <TouchableVibe key={`vibe-${vibe}`} vibe={vibe} />
        ))}
      </View>
    </View>
  );
}

Answered By – Shawn Yap

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published