1

I am running an map function on my array which returns JSX in which I have a touchable opacity and inside that some text. So that touchable opacity is applied to each element of the array.

array.map((item, index) => {
     <TouchableOpacity onPress={someFunction} > 
          <View>
               <Text>{item.data}</Text>
          </View>
     </TouchableOpacity>
)}

Consider I have 4 array elements, I want to click on one and change the background color of only one (the selected) or the selected plus another touchableopacity. How can I achieve this?

Haris Ali
  • 55
  • 1
  • 9

1 Answers1

1

You have to create a ref for each element and then set the style on click. Here is a working demo on snack : Dynamic ref with functional component

I worked with a functional compoennt, but if you are using a class, here a link to show you how to implements it : Dynamic ref with Class component

And in case Snack doesn't works, here is the code :

import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity } from 'react-native';

export default function App() {
  const myRefs = React.useRef([]);

  const items = [
    {
      id:0,
      name:"Item1"
    },
    {
      id:1,
      name:"Item2"
    },
    {
      id:2,
      name:"Item3"
    }
  ];

  const buildView = () => {
      return items.map(item =>{
        return(
          <TouchableOpacity onPress={() => highlight(item.id)}>
            <View ref={el => myRefs.current[item.id] = el}>
              <Text>{item.name}</Text>
            </View>
          </TouchableOpacity>

        )
      });
  }

  const highlight = (itemId) => {
    myRefs.current[itemId].setNativeProps({style: {backgroundColor:'#FF0000'}});
  }

    const resetColors = () => {
        myRefs.current.forEach(ref => 
            ref.setNativeProps({style:{backgroundColor:'transparent'}})
        );
  }

  return (
    <View>
      {buildView()}
      <Button title="Next question" onPress={resetColors} />
    </View>
  );
}

I create a ref fow each view and onPress, I just change its style. Do whatever you want in the highlight method.

Quentin Grisel
  • 4,794
  • 1
  • 10
  • 15
  • And if I wanted to reset the background color for the view? Basically I am building this for a quiz app where the selected option's background color should update to green or red if it was correct or wrong respectively. This worked for the first question but for the next question one of the views had the background color set to '#FF0000' – Haris Ali May 11 '20 at 09:30
  • @HarisAli you can simply loop over your array of refs and reset the color. I edited my post and the snack to add a button that do that – Quentin Grisel May 11 '20 at 11:32