The Gallery component is an unopinionated component designed to build zoomable galleries with behavior similar to Telegram. It uses a Flatlist-like API and supports pinch gestures, double-tap to zoom, tap-to-item navigation, and custom scroll transitions.
Key Implementation Details
- Performance: Like
Flatlist, you should memoize your renderItem and keyExtractor callbacks using useCallback to maintain high performance. - Sizing: Each cell is sized to match the dimensions of the
Gallery component itself. - Image Fitting: When rendering images, use the
fitContainer utility to calculate the appropriate size for the image based on its aspect ratio and the container dimensions.
import React, { useCallback, useRef } from 'react';
import {
stackTransition,
Gallery,
type GalleryType,
fitContainer
} from 'react-native-zoom-toolkit';
import { Image, useWindowDimensions } from 'react-native';
const images = ['url1', 'url2'];
const GalleryExample = () => {
const ref = useRef<GalleryType>(null);
const renderItem = useCallback((item: string, index: number) => {
// Use fitContainer to handle image sizing
return <GalleryImage uri={item} index={index} />;
}, []);
const keyExtractor = useCallback((item: string, index: number) => {
return `${item}-${index}`;
}, []);
const transition = useCallback(stackTransition, []);
return (
<Gallery
ref={ref}
data={images}
keyExtractor={keyExtractor}
renderItem={renderItem}
customTransition={transition}
/>
);
};
// Helper component example
const GalleryImage = ({ uri, index }: { uri: string; index: number }) => {
const { width, height } = useWindowDimensions();
const [resolution, setResolution] = React.useState({ width: 1, height: 1 });
const size = fitContainer(resolution.width / resolution.height, { width, height });
return (
<Image
source={{ uri }}
style={size}
onLoad={(e) => {
setResolution({
width: e.nativeEvent.source.width,
height: e.nativeEvent.source.height,
});
}}
/>
);
};