react-photo-view

repository·master·Indexed 23 days ago

https://github.com/minjieliu/react-photo-view

A lightweight, high-performance React component for photo and media previews. It features a lightbox-style interface with natural touch gestures, adaptive image scaling, and support for custom HTML elements like videos. The library provides PhotoProvider for state management, PhotoView for triggering previews, and PhotoSlider for advanced controlled previews, along with customizable toolbars, overlays, and animation settings.

Tokens
8.2K
Snippets
14
Records
35
Agent score
82%

What's inside react-photo-view

  1. Overview of react-photo-view features

    master

    react-photo-view is a lightweight (7KB Gzipped) image preview component with the following capabilities:

    • Touch Gestures: Supports dragging, panning, physics-based sliding, and pinch-to-zoom.
    • Smooth Animations: Seamless transitions for opening, closing, rebounding, and edge-touching.
    • Adaptive Layout: Images automatically adapt to an appropriate initial size and resize dynamically.
    • Custom Content: Supports previewing <video /> or any arbitrary HTML elements.
    • Keyboard Navigation: Fully optimized for desktop users.
    • Extensibility: Supports custom node extensions for features like full-screen preview, rotation controls, and image descriptions.
    • Developer Friendly: Built with typescript and supports Server-Side Rendering (SSR).
  2. Key features of react-photo-view

    master

    The library provides a high-fidelity image preview experience with the following capabilities:

    • Touch Gestures: Supports dragging, panning, physical-effect sliding, and pinch-to-zoom (two-finger zoom at specific locations).
    • Smooth Animations: Includes seamless transitions for opening, closing, rebounding, and edge-touching.
    • Adaptive Layout: Automatically calculates appropriate initial presentation sizes and adapts to window resizing.
    • Custom Content Support: Can preview <video /> tags or any arbitrary HTML elements.
    • Desktop Support: Full keyboard navigation support.
    • Extensibility: Supports custom node extensions to implement features like full-screen mode, rotation controls, or image captions.
    • Developer Friendly: Built with TypeScript, supports Server-Side Rendering (SSR), and is lightweight (~7KB Gzipped).
  3. How PhotoProvider and PhotoView work together

    master

    The library uses a provider-consumer pattern to manage image galleries:

    • PhotoProvider: Serves as the context provider. It manages the state for a collection of images. Any PhotoView component nested within the same PhotoProvider is automatically included in the same preview gallery, allowing users to swipe through images sequentially.
    • PhotoView: Acts as the trigger for an individual image. It requires a src prop which points to the full-size image to be displayed in the previewer. It wraps a child element (like an <img> or a custom component) that serves as the clickable thumbnail.
  4. Basic usage of react-photo-view

    master

    To implement image previews, use the PhotoProvider and PhotoView components.

    1. Wrap your application or a specific section with PhotoProvider. This acts as a boundary; all PhotoView components inside it are treated as a single gallery in their rendering order.
    2. Wrap the trigger element (e.g., an <img> tag) with PhotoView and provide the src prop pointing to the full-size image.
    3. Important: You must import the component styles: import 'react-photo-view/dist/react-photo-view.css';.
    import { PhotoProvider, PhotoView } from 'react-photo-view';
    import 'react-photo-view/dist/react-photo-view.css';
    
    export default function App() {
      return (
        <PhotoProvider>
          <PhotoView src="/1.jpg">
            <img src="/1-thumbnail.jpg" alt="" />
          </PhotoView>
        </PhotoProvider>
      );
    }
  5. Quick start with PhotoProvider and PhotoView

    master

    To use react-photo-view, you must first import the CSS file at your application's entry point.

    Wrap your image list in a <PhotoProvider> to create a gallery boundary. Inside, wrap each trigger element (like an <img>) with a <PhotoView> component and provide the src prop. When a user clicks a <PhotoView> child, the library locates the image in the provider's sequence and opens the preview.

    Note: To optimize memory, react-photo-view only keeps three images loaded in the DOM at a time.

    import 'react-photo-view/dist/react-photo-view.css';
    import { PhotoProvider, PhotoView } from 'react-photo-view';
    
    export default function MyComponent() {
      return (
        <PhotoProvider>
          <div className="foo">
            {images.map((item, index) => (
              <PhotoView key={index} src={item}>
                <img src={item} alt="" />
              </PhotoView>
            ))}
          </div>
        </PhotoProvider>
      );
    }
  6. Quick start with react-photo-view

    master

    To implement basic image preview functionality, you need to use two main components: PhotoProvider and PhotoView.

    1. Wrap your application or a specific section with PhotoProvider. This component acts as a boundary; all PhotoView components inside it are treated as a single gallery group.
    2. Wrap the trigger element (e.g., an <img> tag) with PhotoView and provide the high-resolution image URL via the src prop.
    3. Ensure you import the required CSS: import 'react-photo-view/dist/react-photo-view.css';.

    When a user clicks the element inside PhotoView, the library will locate the corresponding image in the gallery and open the previewer.

    import { PhotoProvider, PhotoView } from 'react-photo-view';
    import 'react-photo-view/dist/react-photo-view.css';
    
    export default function App() {
      return (
        <PhotoProvider>
          <PhotoView src="/1.jpg">
            <img src="/1-thumbnail.jpg" alt="" />
          </PhotoView>
        </PhotoProvider>
      );
    }
  7. Configure PhotoProvider options

    master

    The <PhotoProvider> component accepts several configuration props to customize the gallery behavior:

    • loop: Controls loop behavior. Can be a boolean to enable/disable, or a number to specify the number of loops (default is 3).
    • maskOpacity: Sets the default transparency of the mask (value between 0-1).
    • bannerVisible: If false, hides the top area (toolbar area).
    • pullClosable: If false, prevents closing the gallery by pulling down (default true).
    • maskClosable: If false, prevents closing the gallery by clicking on the mask (default true).
    • overlayRender: Function to implement custom overlay nodes. The return value signature is the same as toolbarRender.
    <PhotoProvider 
      loop={4} 
      maskOpacity={0.5} 
      bannerVisible={false} 
      pullClosable={false} 
      maskClosable={false} 
    />
  8. Use PhotoSlider for advanced controlled previews

    master

    While <PhotoProvider> is sufficient for most use cases, <PhotoSlider> provides a more granular API for advanced custom controls. It inherits all props from <PhotoProvider> and adds:

    • images: list of images DataType[]
    • visible: controlled visibility boolean
    • onClose: close event callback () => void
    • afterClose: callback after closing animation () => void
    • index: controlled current index number
    • onIndexChange: index change callback (index: number) => void

    To control the slider, you must manage visible and index in your own state and pass them to the component.

    export default function MyComponent() {
      const [visible, setVisible] = useState(false);
      const [index, setIndex] = useState(0);
    
      return (
        <>
          <Button onClick={() => setIndex(2)}>setIndex(2)</Button>
          <Button onClick={() => setVisible(true)} primary>
            Click
          </Button>
    
          <PhotoSlider
            images={images.map((item) => ({ src: item, key: item }))}
            visible={visible}
            onClose={() => setVisible(false)}
            index={index}
            onIndexChange={setIndex}
          />
        </>
      );
    }
  9. Use PhotoSlider for advanced controlled access

    master

    While PhotoProvider is sufficient for most cases, PhotoSlider provides a more advanced API for manual control of the gallery state. It inherits all props from PhotoProvider and adds the following:

    • images: DataType[] - The image list.
    • visible: boolean - Controlled visibility state.
    • onClose: () => void - Callback when closed.
    • afterClose: () => void - Callback after the close animation finishes.
    • index: number - Controlled current index.
    • onIndexChange: (index: number) => void - Callback for index changes.

    Example of a controlled PhotoSlider:

    export default function MyComponent() {
      const [visible, setVisible] = useState(false);
      const [index, setIndex] = useState(0);
    
      return (
        <>
          <Button onClick={() => setIndex(2)}>setIndex(2)</Button>
          <Button onClick={() => setVisible(true)} primary>
            Click
          </Button>
    
          <PhotoSlider
            images={images.map((item) => ({ src: item, key: item }))}
            visible={visible}
            onClose={() => setVisible(false)}
            index={index}
            onIndexChange={setIndex}
          />
        </>
      );
    }