react-pageflip

repository·master·Indexed 20 days ago

https://github.com/nodlik/react-pageflip

A React.js wrapper for the StPageFlip library used to create realistic page-turning effects. It provides the HTMLFlipBook component to support both simple images and complex HTML blocks as pages. The library includes configurable sizing, visual effects like shadows, and event hooks such as onFlip and onInit, while allowing programmatic control of the PageFlip instance via React refs.

Tokens
3.9K
Snippets
11
Records
12
Agent score
72%

What's inside react-pageflip

  1. Use React.forwardRef for custom Page components

    master

    If you want to define your pages as custom React components, you must use React.forwardRef to pass a ref to the underlying DOM element. This allows the HTMLFlipBook engine to interact with the page elements correctly.

    const Page = React.forwardRef((props, ref) => {
        return (
            <div className="demoPage" ref={ref}>
                {/* ref required */}
                <h1 >Page Header</h1 >
                <p>{props.children}</p>
                <p>Page number: {props.number}</p>
           </div >
        );
    });
    
    function MyBook(props) {
        return (
            <HTMLFlipBook width={300} height={500}>
                <Page number="1">Page text</Page>
                <Page number="2">Page text</Page>
                <Page number="3">Page text</Page>
                <Page number="4">Page text</Page>
            </HTMLFlipBook>
        );
    }
  2. Configure HTMLFlipBook with Props

    master

    Use the following props to configure the behavior and appearance of the book:

    PropTypeDefaultDescription
    widthnumber(required)Required width of the page
    heightnumber(required)Required height of the page
    size'fixed' | 'stretch''fixed'Whether the book stretches under the parent element
    minWidthnumberThreshold value for size="stretch"
    maxWidthnumberThreshold value for size="stretch"
    minHeightnumberThreshold value for size="stretch"
    maxHeightnumberThreshold value for size="stretch"
    drawShadowbooleantrueDraw shadows during page flipping
    flippingTimenumber1000Flipping animation time in milliseconds
    usePortraitbooleantrueEnable switching to portrait mode
    startZIndexnumber0Initial value for z-index
    autoSizebooleantrueIf true, the parent element matches the book size
    maxShadowOpacitynumber1Shadow intensity (0 to 1)
    showCoverbooleanfalseIf true, first/last pages are 'hard' and shown in single page mode
    mobileScrollSupportbooleantrueDisables content scrolling when touching the book on mobile
    swipeDistancenumber30Minimum px distance to detect a swipe
    clickEventForwardbooleantrueForwards click events to a and button tags inside pages
    useMouseEventsbooleantrueUses mouse and touch events for flipping
    renderOnlyPageLengthChangebooleanfalseRe-renders ONLY if the number of pages changes (v2.0.0+)
  3. Basic Usage of HTMLFlipBook

    master

    To create a simple page-turning effect, import HTMLFlipBook and wrap your page elements (like divs) inside it. You must provide width and height props.

    import HTMLFlipBook from 'react-pageflip';
    
    function MyBook(props) {
        return (
            <HTMLFlipBook width={300} height={500}>
                <div className="demoPage">Page 1</div >
                <div className="demoPage">Page 2</div >
                <div className="demoPage">Page 3</div >
                <div className="demoPage">Page 4</div >
            </HTMLFlipBook>
        );
    }
  4. Access PageFlip methods via Ref

    master

    To programmatically control the book (e.g., flipping pages), use a React useRef to capture the HTMLFlipBook component. You must call .pageFlip() on the ref's current value to access the PageFlip API.

    function DemoBook() {
        const book = useRef();
    
        return (
            <>
                <button onClick={() =>
                    book.current.pageFlip().flipNext()}>
                    Next page
                </button>
    
                <HTMLFlipBook
                    ref={book}
                    width={300}
                    height={500}
                >
                    {/* ... pages */}
                </HTMLFlipBook>
            </>
        );
    }
  5. Handle HTMLFlipBook Events

    master

    You can listen to various lifecycle and interaction events. The event object contains data (the value associated with the event) and object (the PageFlip instance).

    ```jsx
    function DemoBook() {
        const onFlip = useCallback((e) => {
            console.log('Current page: ' + e.data);
        }, []);
    
        return (
            <HTMLFlipBook
                onFlip={onFlip}
            >
                {/* ... pages */}
            </HTMLFlipBook>
        )
    }

    Available Events:

    • onFlip: number — Triggered by page turning.
    • onChangeOrientation: 'portrait' | 'landscape' — Triggered when orientation changes.
    • onChangeState: 'user_fold' | 'fold_corner' | 'flipping' | 'read' — Triggered when the book state changes.
    • onInit: ({page: number, mode: 'portrait' | 'landscape'}) — Triggered when the book is initialized. Listen to this before calling loadFrom... methods.
    • onUpdate: ({page: number, mode: 'portrait' | 'landscape'}) — Triggered when pages are updated via updateFrom... methods.
  6. Configure the PageFlip component with IFlipSetting

    master

    The IFlipSetting interface defines the configuration options for the react-pageflip component. Use these properties to control the book's dimensions, animation behavior, shadow effects, and interaction modes.

    Key Configuration Groups

    Sizing and Layout

    • size: Determines if the book is 'fixed' or 'stretch' under the parent element.
    • width, height: Dimensions of the book.
    • minWidth, maxWidth, minHeight, maxHeight: Constraints for the book size.
    • autoSize: If true, the parent element will match the size of the book.
    • usePortrait: Enables switching to portrait mode.

    Visual Effects

    • drawShadow: Boolean to enable/disable shadows during page flipping.
    • maxShadowOpacity: Controls shadow intensity (0 to 1).
    • showPageCorners: If true, folds the corners of the book when the mouse pointer is over them.
    • showCover: If true, the first and last pages are treated as hard covers and shown in single-page mode.

    Interaction and Animation

    • startPage: The page number from which to start viewing.
    • flippingTime: Duration of the flipping animation.
    • useMouseEvents: Enables mouse and touch events for flipping.
    • swipeDistance: Distance required for a swipe to trigger a flip.
    • disableFlipByClick: If true, clicking the whole book is locked; flipping only works via corners.
    • clickEventForward: If true, clicks on child elements (buttons, links) are forwarded.
    • mobileScrollSupport: If true, content scrolling is enabled on mobile devices when touching the book.
    const settings: IFlipSetting = {
      startPage: 0,
      size: 'stretch',
      width: 800,
      height: 600,
      drawShadow: true,
      maxShadowOpacity: 0.5,
      showCover: true,
      useMouseEvents: true,
      // ... other properties
    };
  7. Handle HTMLFlipBook events

    master

    The HTMLFlipBook component supports several event callbacks passed through the IEventProps interface. These allow you to react to the state of the book:

    • onFlip: Triggered when a page is flipped.
    • onChangeOrientation: Triggered when the orientation changes.
    • onChangeState: Triggered when the state of the book changes.
    • onInit: Triggered when the PageFlip instance is initialized.
    • onUpdate: Triggered when the book is updated.
    <HTMLFlipBook
      className="book"
      style={{ width: '500px', height: '700px' }}
      onFlip={(e) => console.log('Flipped!', e)}
      onChangeState={(e) => console.log('State changed:', e)}
      onInit={(e) => console.log('Initialized:', e)}
    >
      <div className="page">Page 1</div>
      <div className="page">Page 2</div>
    </HTMLFlipBook>
  8. Handle PageFlip events with IEventProps

    master

    The react-pageflip component provides several event hooks via the IEventProps interface to respond to book state changes and lifecycle events.

    • onInit: Triggered when the book is initialized.
    • onFlip: Triggered when a page flip occurs.
    • onUpdate: Triggered when the book state is updated.
    • onChangeOrientation: Triggered when the page orientation (portrait/landscape) changes.
    • onChangeState: Triggered when the internal page state changes.
    <PageFlip
      onInit={(e) => console.log('Initialized', e)}
      onFlip={(e) => console.log('Flipped', e)}
      onChangeOrientation={(e) => console.log('Orientation changed', e)}
    >
      {/* Pages */}
    </PageFlip>
  9. Access the PageFlip instance via ref

    master

    If you need to call imperative methods on the underlying PageFlip engine (such as manual page navigation or updating the book), you can use a ref on the HTMLFlipBook component.

    The ref provides an object containing a pageFlip() method that returns the actual PageFlip instance.

    Note: The ref type is React.MutableRefObject<PageFlip> (where PageFlip is imported from the page-flip package).

    import React, { useRef } from 'react';
    import { HTMLFlipBook } from 'react-pageflip';
    import { PageFlip } from 'page-flip';
    
    const BookController = () => {
      const flipRef = useRef<{ pageFlip: () => PageFlip }>(null);
    
      const handleNextPage = () => {
        if (flipRef.current) {
          const api = flipRef.current.pageFlip();
          api.flipNext(); // Example method from page-flip
        }
      };
    
      return (
        <>
          <button onClick={handleNextPage}>Next</button>
          <HTMLFlipBook
            ref={flipRef}
            className="book"
            style={{ width: '500px', height: '700px' }}
          >
            <div className="page">Page 1</div>
            <div className="page">Page 2</div>
          </HTMLFlipBook>
        </>
      );
    };
  10. Use the HTMLFlipBook component

    master

    The HTMLFlipBook component is the primary entry point for rendering page flip effects in React. It acts as a wrapper around the StPageFlip library.

    To use it, wrap your page elements (as React children) inside the HTMLFlipBook component. The component requires a className and style prop. It also accepts configuration settings via IFlipSetting and event handlers via IEventProps.

    Key requirements:

    • Each child passed to HTMLFlipBook must be a valid React element that can accept a ref (as the component uses these refs to manage the underlying DOM elements for the flip effect).
    • The component uses React.memo for performance optimization.
    import { HTMLFlipBook } from 'react-pageflip';
    
    function MyBook() {
      return (
        <HTMLFlipBook
          className="book-container"
          style={{ width: '500px', height: '700px' }}
        >
          <div className="page">Page 1</div>
          <div className="page">Page 2</div>
          <div className="page">Page 3</div>
        </HTMLFlipBook>
      );
    }
  11. Reference: IFlipSetting properties

    master

    Complete list of configuration keys for IFlipSetting.

    interface IFlipSetting {
        startPage: number;
        size: 'fixed' | 'stretch';
        width: number;
        height: number;
        minWidth: number;
        maxWidth: number;
        minHeight: number;
        maxHeight: number;
        drawShadow: boolean;
        flippingTime: number;
        usePortrait: boolean;
        startZIndex: number;
        autoSize: boolean;
        maxShadowOpacity: number;
        showCover: boolean;
        mobileScrollSupport: boolean;
        clickEventForward: boolean;
        useMouseEvents: boolean;
        swipeDistance: number;
        showPageCorners: boolean;
        disableFlipByClick: boolean;
    }