pavelbabenko / react-native-awesome-gallery

Performant, native-like, and well-customizable gallery for React Native.
MIT License
494 stars 54 forks source link

feat: set page programmatically #9

Closed troZee closed 3 years ago

troZee commented 3 years ago

Feature: added ability to set page programmatically

Description: In some cases, you would like to go to next page using the other methods than swipe gesture e.g by clicking in the next button.

How to test it:

just add below code to Photos.tsx

import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import { useCallback } from 'react';
import { StyleSheet, View } from 'react-native';
import AwesomeGallery, {
  GalleryRefType,
  RenderItemInfo,
} from 'react-native-awesome-gallery';
import * as React from 'react';
import type { NavParams } from '../navigation/types';
import { SharedElement } from 'react-navigation-shared-element';
import FastImage from 'react-native-fast-image';

const renderItem = ({
  index,
  item,
  setImageDimensions,
}: RenderItemInfo<{ uri: string }>) => {
  return (
    <SharedElement id={`${index}`} style={StyleSheet.absoluteFillObject}>
      <FastImage
        source={{ uri: item.uri }}
        style={StyleSheet.absoluteFillObject}
        resizeMode={FastImage.resizeMode.contain}
        onLoad={(e) => {
          const { width, height } = e.nativeEvent;
          setImageDimensions({ width, height });
        }}
      />
    </SharedElement>
  );
};

export const Photos = () => {
  const { setParams, goBack } = useNavigation();
  const { params } = useRoute<RouteProp<NavParams, 'Photos'>>();
  const ref = React.useRef<GalleryRefType>(null);
  const onIndexChange = useCallback(
    (index) => {
      setParams({ index });
    },
    [setParams]
  );

  React.useEffect(() => {
    setTimeout(() => {
      ref.current?.setPage(1);
    }, 1000);
  }, []);

  return (
    <View style={styles.container}>
      <AwesomeGallery
        ref={ref}
        data={params.images.map((uri) => ({ uri }))}
        keyExtractor={(item) => item.uri}
        renderItem={renderItem}
        initialIndex={params.index}
        onIndexChange={onIndexChange}
        onSwipeToClose={goBack}
      />
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
});
pavelbabenko commented 3 years ago

I've added this feature with better typing. I'm closing this PR

troZee commented 3 years ago

@pavelbabenko Could you provide an example, how to change page programmatically ? bc I could not find it in documentation.

troZee commented 3 years ago

@pavelbabenko I see, you have added it in the mean time https://github.com/Flair-Dev/react-native-awesome-gallery/commit/380c0821613c465558d092ad57c177311c9afb88

Thank you <3

pavelbabenko commented 3 years ago

@troZee New version is released. Note that setPage is renamed to setIndex. README is updated with example as well

troZee commented 3 years ago

@pavelbabenko thank you so much <3