I am making an animated heart icon in my react native app. Currently, I have a generic Button
which accepts an icon
prop, letting it display an icon:
<Button
color="white"
icon={selected ? (<MaterialCommunityIcons name="selected" size={24} />) :
(<MaterialCommunityIcons name="unselected" size={24} />)}
onPress={async () => {
const newSelectedStates = [...selectedStates];
newSelectedStates[index] = !selected;
setSelectedStates(newSelectedStates);
// make some API requests with the async behavior
}}
/>
So currently, I have multiple buttons. The states of whether these icons are selected or not is held in a parent array. In the above code, selected
is one element from that array, corresponding to the relevant button.
When I click the button, it edits the state array, therefore rendering a new icon.
What I would like to do is add an animated heart when I click the button, rather than simply rendering one of two icons based on the state. It seems like good design to have something reusable and DRY. I believe having an external component, AnimatedHeart
, which accepts a selected
prop is the way to go. However, I am not sure on how I can handle the onPress
functionality to also animate the heart itself?
For instance, if I define an animated heart component, and include an onPress
inside it, I now have to juggle two onPress
's which seems like poor design.
Does anyone know how I can seamlessly link these two together? I'm less interested in the actual heart animation itself, and more on getting everything working. I'm also not keen on creating the onPress
for the heart animation at the parent level because that seems less reusable. I feel it would be better to have the animation encapsulated within the heart component itself.
I may need two onPress
's though ultimately, since each button click should do a unique thing (for instance a different API call), and the heart press should be consistent