Home > Blockchain >  REACT NATIVE How can I highlight an item with a scrollview and increment/decrement the highlighted i
REACT NATIVE How can I highlight an item with a scrollview and increment/decrement the highlighted i

Time:03-22

I am building an 'Initiative Tracker' for home use. My goal is to have the first item at the top of the list highlighted by default and use a counter that keeps track of the turns to highlight the item to correspong with its turn. Eg. When the ' ' button is pressed, the next item should be highlighted and the previous item should return to normal. I am currently using the map function to display an array. I feel like there should be a way to use the index and a style to achieve what I want, but I've had no luck so far.

Thanks in advance for any help or suggestions!

related code below:

let Encounter1Array = [
  { name: "goblin1", init: 5 },
  { name: "goblin2", init: 8 },
  { name: "goblin3", init: 15 },
  { name: "goblin4", init: 3 },
  { name: "goblin5", init: 9 },
];

function InitiativeTrackerScreen() {
  const [encounter, setEncounter] = useState(Encounter1Array);
  encounter.sort(function (x, y) {
    return y.init - x.init;
  });
  return (
    <KeyboardAvoidingView style={styles.wrapper}>
      <ScrollView>
        {encounter.map((item, index) => {
          return (
            <View key={index}>
              <TouchableOpacity style={styles.ItemDisplayContainer}>
                <View>
                  <View>
                    <Text style={{ fontStyle: "italic", fontSize: 16 }}>
                      {item.name}
                    </Text>
                  </View>
                  <View>
                    <Text style={{ fontSize: 12 }}>
                      Initiative: {item.init}
                    </Text>
                  </View>
                </View>
              </TouchableOpacity>
            </View>
          );
        })}
      </ScrollView>
    </KeyboardAvoidingView>
  );
}

CodePudding user response:

You need extra state to keep track of the index of the element you want to highlight. Then you can use a conditional statement to match to right index and switch its style.

const P = ({ list }) => {
  const [current, setCurrent] = useState(0);

  return list.map((item, i) => 
    <View style={i === current ? highlightStyle : style}>
      <Button onPress={() => setCurrent(current   1)}>
        {" "}
      </Button>
      {item}
    </View>
  );
};
  • Related