I am using React native and I have a loop in which some property types are being displayed,
i created only one state for it because property types are being fetched from DB. What i want to do is to show them selected. kindly show me a way to achieve it.
const [propBCol, setPropBCol] = useState('#EDEDEE');
const [propTCol, setPropTCol] = useState('#000000');
{propType.map((item, index) => {
return (
<TouchableOpacity style={{
backgroundColor: propBCol,
...ListingFilterStyles.filterAnyBtn,
...ListingFilterStyles.btnMale,
}}
onPress={() => proptypes(item)}>
<Text style={{color: propTCol}}>{item.value}</Text>
</TouchableOpacity>
);
})}
the propTypes function:
const proptypes = item => {
setPropBCol('red');
setPropTCol('White')
}
enter code here
How can i change the selected item color, by above code all are item colors are being changed
CodePudding user response:
const [propBCol, setPropBCol] = useState('#EDEDEE');
const [propTCol, setPropTCol] = useState('#000000');
const [selected, setSelected] = useState([]);
{propType.map((item, index) => {
return (
<TouchableOpacity style={{
backgroundColor: selected.includes(index) ? propBCol : item.propBCol,
...ListingFilterStyles.filterAnyBtn,
...ListingFilterStyles.btnMale,
}}
onPress={() => proptypes(index)}>
<Text style={{color: selected.includes(index) ? propTCol : item.propTCol}}>{item.value}</Text>
</TouchableOpacity>
);
})}
const proptypes = (index) => {
setSelected(prev => {
return [
...prev,
index
]
})
}
CodePudding user response:
You should not declare a state for each one of the propType you are receiving. What you can do is, you can add a key inside the object that you are getting and saving it inside the state.
And on press you can change the value of the checked key using simple index values of the array. You have to pass the data inside the method and write the method as below
const propsTypes = (item, index) => {
var propTypesVar = [...propTypes]
propTypesVar[index].propBCol= <<Your desired color>>
propTypesVar[index].propTCol= <<Your desired color>>
setPropType(propTypesVar)
}
After that the value of propBCol will be inside the object of your propType array and you can render anything to show the user if the value is selected or not i.e.
{propType.map((item, index) => {
return (
<TouchableOpacity
style={{
backgroundColor: item.propBCol,
...ListingFilterStyles.filterAnyBtn,
...ListingFilterStyles.btnMale,
}}
onPress={() => proptypes(item)}>
<Text style={{color: item.propTCol}}>{item.value}</Text>
</TouchableOpacity>
);
})}