Closed fukemy closed 1 year ago
Hey there, I am not maintaining this package due to time constraints.
Here's a component that you can use
Install react-native-reanimated
. Follow the docs.
Create a file with name of your choice, let's say LikeButton.tsx
Paste the below code in the file
// Packages imports
import { useEffect } from "react";
import { Pressable, StyleSheet } from "react-native";
import Animated, {
useSharedValue,
withSpring,
useAnimatedStyle,
Extrapolate,
interpolate,
} from "react-native-reanimated";
export interface LikeButtonProps {
// Required
liked: boolean;
// Required
onPress?: () => void;
// Optional (A function that returns a JSX.Element)
unLikedComponent: () => JSX.Element;
// Optional (A function that returns a JSX.Element)
likedComponent: () => JSX.Element; // Optional
}
export default function LikeButton(props: LikeButtonProps) {
// Destructure Props
const {
liked = false,
onPress = () => {},
unLikedComponent,
likedComponent,
} = props;
// This is a shared value for animation
const isLikedSharedValue = useSharedValue(liked !== undefined && liked === true ? 1 : 0);
// Check whether the component should be controlled or uncontrolled
const controlled = liked !== undefined;
// useEffect to detect when `liked` prop changes
// If component is controlled then animate according to `liked` prop
useEffect(() => {
if (controlled) isLikedSharedValue.value = withSpring(liked ? 1 : 0);
}, [liked, controlled, isLikedSharedValue]);
// Animated Styles for the upper like button
const outlineStyles = useAnimatedStyle(() => {
return {
transform: [
{
scale: interpolate(isLikedSharedValue.value, [0, 1], [1, 0], Extrapolate.CLAMP),
},
],
};
});
// Animated Styles for the bottom like button
const fillStyles = useAnimatedStyle(() => {
return {
transform: [
{
scale: isLikedSharedValue.value,
},
],
opacity: isLikedSharedValue.value,
};
});
// If Component is uncontrolled, just invert the isLikedSharedValue value
// Other wise do nothing
const onComponentPress = async () => {
if (!controlled) isLikedSharedValue.value = withSpring(isLikedSharedValue.value ? 0 : 1);
if (onPress instanceof Function) onPress();
};
// Render
return (
<Pressable onPress={onComponentPress}>
<Animated.View style={[StyleSheet.absoluteFillObject, outlineStyles]}>
{unLikedComponent ? unLikedComponent() : null}
</Animated.View>
<Animated.View style={fillStyles}>
{likedComponent ? likedComponent() : null}
</Animated.View>
</Pressable>
);
}
// Local States
const [isLiked, setIsLiked] = useState(false);
<LikeButton
// To tell the component, whether to show like button or unlike button
liked={isLiked}
// handle onPress of like/unlike button
onPress={() => setIsLiked(!isLiked)}
// component to show for liked state
likedComponent={() => <AntDesign name="heart" size={24} color="red" />}
// component to show for unliked state
unLikedComponent={() => <AntDesign name="hearto" size={24} color="black" />}
/>
Here's a Snack that has the implementation.
I got this error
plz help