$ git show stories-cube
Stories cube
Swipe between stories and they rotate like the faces of a 3D cube.
Inspired by InstagramFrom William Candillon’s “Can it be done in React Native?” series. The code here is a simplified rewrite for Reanimated 4 and 3.
This snippet uses APIs that didn’t change between versions, so the same code runs on Reanimated 4 and 3.
const x = useSharedValue(0);
const onScroll = useAnimatedScrollHandler(e => { x.value = e.contentOffset.x; });
function Story({ index, children }) {
const style = useAnimatedStyle(() => {
const offset = index * width - x.value; // 0 = on screen, +width = next page
const angle = interpolate(offset, [-width, 0, width], [-90, 0, 90], Extrapolation.CLAMP);
const edge = offset > 0 ? -width / 2 : width / 2; // rotate around the shared edge
return {
transform: [
{ perspective: 1000 },
{ translateX: edge }, { rotateY: angle + 'deg' }, { translateX: -edge },
],
};
});
return <Animated.View style={[{ width, height }, style]}>{children}</Animated.View>;
}
// <Animated.ScrollView horizontal pagingEnabled onScroll={onScroll} scrollEventThrottle={16}>
// Flip the sign of angle if the cube opens inward on your setup.