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.