$ git show fly-to-cart

Fly to cart

Advanced/anim fly-to-cart

Add to cart and a copy of the product image arcs across the screen into the cart icon, which bumps when it lands.

Main · New Architecture only · worklets live in react-native-worklets
measureuseAnimatedRefscheduleOnRN
fly-to-cart.tsx · reanimated 4
import { scheduleOnRN, scheduleOnUI } from 'react-native-worklets';

// Reanimated 4: scheduleOnUI and scheduleOnRN replace runOnUI and runOnJS
const imageRef = useAnimatedRef();
const cartRef = useAnimatedRef();
const p = useSharedValue(0);
const from = useSharedValue({ x: 0, y: 0 }), to = useSharedValue({ x: 0, y: 0 });
const bump = useSharedValue(1);
const [flying, setFlying] = useState(false);

const landed = () => { setFlying(false); addToCart(product); };

const fly = () => {
  setFlying(true);
  scheduleOnUI(() => {
    const a = measure(imageRef), b = measure(cartRef);
    if (!a || !b) return;
    from.value = { x: a.pageX, y: a.pageY };
    to.value = { x: b.pageX + b.width / 2 - a.width / 2, y: b.pageY + b.height / 2 - a.height / 2 };
    p.value = 0;
    p.value = withTiming(1, { duration: 700, easing: Easing.inOut(Easing.quad) }, (done) => {
      if (!done) return;
      bump.value = withSequence(withTiming(1.3, { duration: 100 }), withSpring(1, { damping: 6 }));
      scheduleOnRN(landed);
    });
  });
};

const clone = useAnimatedStyle(() => {
  const t = p.value;
  return {
    position: 'absolute', left: 0, top: 0,
    transform: [
      { translateX: from.value.x + (to.value.x - from.value.x) * t },
      { translateY: from.value.y + (to.value.y - from.value.y) * t - Math.sin(Math.PI * t) * 120 },
      { scale: 1 - 0.75 * t },
    ],
    opacity: t < 0.95 ? 1 : 0,
  };
});
const cart = useAnimatedStyle(() => ({ transform: [{ scale: bump.value }] }));

<Animated.View ref={cartRef} style={cart}><CartIcon /></Animated.View>
<Animated.Image ref={imageRef} source={product.image} style={styles.image} />
<Button title="Add to cart" onPress={fly} />
{flying && <Animated.Image pointerEvents="none" source={product.image} style={[styles.image, clone]} />}