I want to select multiple hearts as per user will going to select. In other words, When a user clicks on multiple hearts then multiple hearts should be selected or the background color should be green. However, it is selecting one at a time.
I know that if multiple hearts will select then needs to store them in an array and map through it, then the nesting map will increase more hearts as the user will click.
Is there any way to solve this issue? I am stuck for a lot of hours đ
2
Answers
Simply you can have one state which is storing selected hearts index.
For example:
And whenever click every heart, check those index included in above index Array or not. If included, it means current heart is already selected, and you are trying to click it again to be non-selected, so you need to remove that index from the
selectedHeartIndex
array, and if not included, it means, it’s not selected before, so you need to add those index to that array to select that heart. Here is the code.And finally, pass heartIndexClicked props to your child component(EachHeart) with this boolean value
selectedHeartIndex.filter((inx) => inx === index).length > 0
You need not have isLike and heartIndexClicked state in your code.
You should only have to care about the index of the item when it comes to checking the state.
Also, these states are pointless:
Working example
Try the following:
Note: I changed
first10
tovisibleData
. It’s a better name that I already suggested yesterday. I also changed the size from 10 to 15. You should use a variable instead of hard-coding magic numbers.