react-native-instagram-stories

repository·main·Indexed 42 days ago

https://github.com/birdwingo/react-native-instagram-stories

A React Native component for integrating Instagram-style stories into mobile applications. Version 1.3.18 supports a horizontal scrollable list of avatars, image and video stories, and progress tracking via Async Storage. It includes a programmable API via refs for playback control (pause, resume, next/previous) and story management, with optional integrations for react-native-video and FlashList for improved performance.

Tokens
7.3K
Snippets
19
Records
23
Agent score
51%

What's inside react-native-instagram-stories

  1. Configure Storage, Flashlist, and Video integrations

    main

    The component supports several optional integrations to enhance functionality:

    • Progress Tracking: To use the saveProgress prop to save and track seen stories, you must install @react-native-async-storage/async-storage.
    • Performance: If flashlist is installed in your project, the component will automatically use it for the avatars list.
    • Video Support: To display video stories, ensure react-native-video is installed.
  2. Install @birdwingo/react-native-instagram-stories

    main

    Install the package along with its required peer dependencies: react-native-svg, react-native-reanimated, and react-native-gesture-handler.

    npm install react-native-svg
    npm install react-native-reanimated
    npm install react-native-gesture-handler
    npm install @birdwingo/react-native-instagram-stories
  3. Basic Usage of InstagramStories

    main

    To implement the stories component, import InstagramStories and provide a stories array. Each user object in the array requires an id, name, avatarSource, and a stories array containing individual story items.

    import React, { useRef } from 'react';
    import { View } from 'react-native';
    import InstagramStories, { InstagramStoriesPublicMethods } from '@birdwingo/react-native-instagram-stories';
    
    const YourComponent = () => {
    
      // to use public methods: 
      // if using typescript - useRef<InstagramStoriesPublicMethods>( null )
      const ref = useRef( null ); 
    
      const stories = [{
        id: 'user1',
        name: 'User 1',
        avatarSource: { uri: 'user1-profile-image-url' },
        stories: [
          { id: 'story1', source: { uri: 'story1-image-url' } },
          { id: 'story2', source: { uri: 'story1-video-url' }, mediaType: 'video' },
        ],
      }];
    
      // usage of public method
      const setStories = () => ref.current?.setStories( stories );
      
      return (
        <View>
          <InstagramStories
            ref={ref}
            stories={stories}
          />
         <Pressable onPress={setStories}>{/* ... */}</Pressable>
        </View>
      );
    };
    
    export default YourComponent;
  4. Use InstagramStoriesPublicMethods via ref

    main

    You can control the InstagramStories component programmatically using a ref. If using TypeScript, type the ref as InstagramStoriesPublicMethods. One available method is setStories(stories), which allows you to update the stories list dynamically.

    import InstagramStories, { InstagramStoriesPublicMethods } from '@birdwingo/react-native-instagram-stories';
    
    // ... inside component
    const ref = useRef<InstagramStoriesPublicMethods>(null);
    
    const updateStories = (newStories) => {
      ref.current?.setStories(newStories);
    };
  5. Use Public Methods of InstagramStories

    main

    The InstagramStories component exposes several methods to programmatically control the stories player. You can access these via a ref.

    Available Methods

    • Story Management:

      • setStories(stories: InstagramStoryProps[]): Replace current stories with a new set.
      • spliceStories(stories: InstagramStoryProps[], index?: number): Insert new stories at a specific index (defaults to end).
      • spliceUserStories(stories: InstagramStoryProps[], user: string, index?: number): Insert new stories for a specific user.
      • clearProgressStorage(): Clear the progress storage for seen stories.
    • Playback Control:

      • show(id?: string): Show the stories modal. If id is provided, starts at that story; otherwise, starts at the first.
      • hide(): Hide the stories if currently visible.
      • pause(): Pause the current story.
      • resume(): Resume the current story.
      • isPaused(): Returns true if the story is currently paused.
      • goToNextStory(): Go to the next story item.
      • goToPreviousStory(): Go to the previous story item.
      • goToSpecificStory(userId: string, index: number): Jump to a specific index for a user. If index doesn't exist, starts the first story.
    • State Inspection:

      • getCurrentStory(): Returns { userId?: string, storyId?: string } for the currently playing story.
  6. Configure InstagramStoryProps component

    main

    The InstagramStoryProps component (the main component of the library) accepts several props to customize the behavior and appearance of the stories.

    Key Configuration Options

    • Data: stories (required) is an array of InstagramStoryProps objects.
    • Behavior:
      • saveProgress: Boolean to track and save seen stories.
      • loopingStories: Controls looping behavior. Options: 'none' (closes after last story), 'onlyLast' (loops only the last user), or 'all' (restarts from the beginning).
      • isVisible: Boolean to show the modal immediately on load.
      • hideElementsOnLongPress: Hides UI elements when the user long-presses to pause.
    • Styling:
      • avatarSize: Size of the avatars in the list (default 60).
      • storyAvatarSize: Size of avatars in the story header (default 25).
      • backgroundColor: Background color of the container (default '#000000').
      • animationDuration: Duration of story animations in ms (default 10000).
    • Callbacks:
      • onShow: Triggered when a story is shown.
      • onHide: Triggered when a story is hidden.
      • onSwipeUp: Triggered when a user swipes up on a story.
      • onStoryStart / onStoryEnd: Triggered at the start and end of a story lifecycle.
    <InstagramStories
      stories={myStories}
      saveProgress={true}
      loopingStories="onlyLast"
      onStoryStart={(userId, storyId) => console.log(userId, storyId)}
    />
  7. StoryItemProps Reference

    main

    The StoryItemProps interface defines the configuration for individual story items within the component. The id parameter must be unique for every story.

    | Parameter | Type | Required | Default |
    -----------------------|--------------------------|-------------------|-------------------|
    `id` | string | true | |
    `source` | ImageProps['source'] | true | |
    `mediaType` | 'video' | 'image' | `'image'` |
    `animationDuration` | number | false | |
    `renderContent` | () => ReactNode | false | |
    `renderFooter` | () => ReactNode | false | |
  8. InstagramStoryProps Reference

    main

    The InstagramStoryProps interface defines the configuration for the main stories component. The id parameter must be unique for every user.

    | Parameter | Type | Required |
    -----------------------|------------------------|----------------|
    `id` | string | true |
    `avatarSource` | ImageProps['source'] | false |
    `renderAvatar` | () => ReactNode | false |
    `renderStoryHeader` | () => ReactNode | false |
    `onStoryHeaderPress` | () => void | false |
    `name` | string | false |
    `stories` | [StoryItemProps](#storyitemprops)[] | true |
  9. Reference the InstagramStories component props

    main

    The following table lists the available props for the InstagramStories component.

    NameTypeDefaultDescription
    storiesInstagramStoryProps[]requiredAn array of stories.
    saveProgressbooleanfalseWhether to save and track the progress of seen stories.
    avatarBorderColorsstring[]DEFAULT_COLORSBorder colors of story avatars.
    avatarSeenBorderColorsstring[]['#2A2A2C']Border colors of seen story avatars.
    avatarSizenumber60The size of the story avatars.
    storyAvatarSizenumber25The size of the avatars shown in the header of each story.
    avatarListContainerStyleScrollViewProps['contentContainerStyle'] | FlashListPropsStyles for the avatar scroll list container.
    avatarListContainerPropsScrollViewPropsProps for the avatar list ScrollView.
    containerStyleViewStyleStyles for the story container.
    textStyleTextStyleStyles for text elements.
    animationDurationnumber10000Duration of story animations in ms.
    videoAnimationMaxDurationnumberMax duration of video animations in ms. If omitted, the whole video plays.
    backgroundColorstring'#000000'Background color of story container.
    showNamebooleanfalseShow user name under avatar in avatar list.
    nameTextStyleTextStyle{ width: avatarSize + 10 }Styles for name text elements.
    nameTextPropsTextPropsProps for the name Text component.
    videoPropsreact-native-video propsAdditional props for the video component.
    closeIconColorstring'#00000099'Color of story close icon.
    progressColorstring'#00000099'Background color of progress bar item in inactive state.
    progressActiveColorstring'#FFFFFF'Background color of progress bar item in active state.
    modalAnimationDurationnumber800Duration of modal animation (showing/closing).
    storyAnimationDurationnumber800Duration of story animation (swiping left/right).
    mediaContainerStyleViewStyleStyles for media (video or image) container.
    imageStylesImageStyle{ width: WIDTH, aspectRatio: 0.5626 }Styles for the image component.
    imagePropsImagePropsProps applied to the image component.
    isVisiblebooleanfalseWhether to show modal on load.
    headerStyleViewStyleStyles for the story header.
    headerContainerStyleViewStyleStyles for the story header container.
    progressContainerStyleViewStyleStyles for the story progress container.
    hideAvatarListbooleanfalseWhether to hide the avatar scroll list.
    hideElementsOnLongPressbooleanfalseHide all elements when story is paused by long press.
    hideOverlayOnLongPressbooleanhideElementOnLongPressIf true, overlay hides on long press. If false, only header/progress bar hide.
    loopingStories'none' | 'onlyLast' | 'all''none''none': close after last; 'onlyLast': loop last user; 'all': loop all.
    statusBarTranslucentbooleanfalseProperty passed to React Native Modal.
    loaderColorstring'#FFFFFF'Color of the loading spinner.
    loaderBackgroundColorstringBackground color of the loading overlay.
    footerComponentReactNodeCustom component added to the modal.
    imageOverlayViewReactNodeImage overlay component.
    onShow(id: string) => voidCallback when a story is shown.
    onHide(id: string) => voidCallback when a story is hidden.
    onSwipeUp(userId?: string, storyId?: string) => voidCallback when user swipes up.
    onStoryStart(userId?: string, storyId?: string) => voidCallback when story started.
    onStoryEnd(userId?: string, storyId?: string) => voidCallback when story ended.
  10. Use the InstagramStories component

    main

    The InstagramStories component is the main entry point for rendering an Instagram-style stories interface. It manages an avatar list and a modal for viewing stories. It supports progress saving, custom styling for avatars, and fine-grained control over story playback via a ref.

    Key Props

    • stories: An array of story data objects.
    • saveProgress: Boolean indicating whether to persist story viewing progress in storage (default: false).
    • isVisible: Boolean to control the visibility of the story modal.
    • hideAvatarList: Boolean to hide the avatar list (default: false).
    • avatarSize: Size of the avatars in the list.
    • animationDuration: Duration for story transitions.
    • videoProps: Configuration passed to the video player.
    • videoAnimationMaxDuration: Maximum duration for video animations.
    • backgroundColor: Background color of the story modal.
    • closeIconColor: Color of the close icon in the modal.
    import InstagramStories from '@birdwingo/react-native-instagram-stories';
    
    // ... inside your component
    <InstagramStories 
      stories={myStories} 
      saveProgress={true} 
      isVisible={true} 
    />
  11. Use StoryModalPublicMethods

    main

    The StoryModalPublicMethods type defines the API available to control the story modal programmatically. These methods allow you to manipulate the playback and navigation of the stories.

    export type StoryModalPublicMethods = {
      show: ( id: string ) => void;
      hide: () => void;
      pause: () => void;
      resume: () => void;
      isPaused: () => boolean;
      goToPreviousStory: () => void;
      goToNextStory: () => void;
      getCurrentStory: () => { userId?: string, storyId?: string };
      goToSpecificStory: ( userId: string, index?: number ) => void;
    };