So I am displaying 5 stars. They are all gray on default when they are not selected. When I click on the star, I want the background color to change of the View but it is not changing after clicking it. Also, if I click star 3, I want the stars before star 3 to also change the background color. But nothing is working.
I used console.log to view the changed list when handleStarClicked runs and it saves the changes but not sure what is going on. Would really appreciate some help, please
const stars = [{ id: 0, selected: false }, { id: 1, selected: false }, { id: 2, selected: false }, { id: 3, selected: false }, { id: 4, selected: false }];
const [holdStars, setHoldStars] = useState(stars);
const handleStarClicked = (id) => {
for (let i = 0 ; i < holdStars.length; i ) {
if (i <= id) {
holdStars[i].selected = true;
} else {
holdStars[i].selected = false;
}
}
setHoldStars(holdStars);
}
return (
<FlatList
data={holdStars}
horizontal
scrollEnabled={false}
renderItem={({ item }) =>
<Pressable onPress={() => handleStarClicked(item.id)} className="ml-1 p-1 rounded-xl items-center justify-center" style={{ backgroundColor: item.selected ? "#6ECCAF" : "#CCCCCC" }}>
<Icon name="star" type="AntDesign" size={32} color="white" />
</Pressable>
}
/>
)
CodePudding user response:
The issue here is that you are modifying the holdStars array directly in the handleStarClicked function and that is causing the issue. Try this :
const handleStarClicked = (id) => {
const newHoldStars = [...holdStars]; // create a new copy of the holdStars array
for (let i = 0 ; i < newHoldStars.length; i ) {
if (i <= id) {
newHoldStars[i].selected = true;
} else {
newHoldStars[i].selected = false;
}
}
setHoldStars(newHoldStars);
}