Nodlik / react-pageflip

Simple React.js wrapper for StPageFlip library, for creating realistic and beautiful page turning effect
https://nodlik.github.io/react-pageflip/
MIT License
476 stars 91 forks source link

pageFlip() returning undefined #15

Closed JayV30 closed 3 years ago

JayV30 commented 3 years ago

Running into an issue with using a ref to access the methods.

In the example below, bookRef.current.pageFlip is a function, but calling that function returns undefined - so I cannot access the methods in the way described in the documentation.

Any suggestions?

(PS thanks for the project.. good stuff)

import React, { useState, useRef, useEffect } from 'react';
import HTMLFlipBook from 'react-pageflip';

const App = () => {
  const [currentPageNum, setCurrentPageNum] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const bookRef = useRef();

  const onPageTurn = (e) => {
    setCurrentPageNum(e.data);
  }

  useEffect(() => {
    if (bookRef && bookRef.current) {
      setTotalPages(bookRef.current.pageFlip().getPageCount()); // throws error b/c pageFlip() returns undefined!
    }
  }, [bookRef]);

  return (
    <HTMLFlipBook width={300} height={500} ref={bookRef}>
      <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>
  );
};

export default App;
JayV30 commented 3 years ago

I worked around this using the onInit event instead and it is working acceptably. Thanks.

import React, { useState, useRef, useCallback } from 'react';
import HTMLFlipBook from 'react-pageflip';

const App = () => {
  const [currentPageNum, setCurrentPageNum] = useState(0);
  const [totalPages, setTotalPages] = useState(0);
  const bookRef = useRef();

  const onPageTurn = (e) => {
    setCurrentPageNum(e.data);
  }

  const onInit = useCallback((e) => {
    if (bookRef && bookRef.current) {
      setTotalPages(bookRef.current.pageFlip().getPageCount());
    }
  }, []);

  return (
    <HTMLFlipBook width={300} height={500} ref={bookRef} onInit={onInit}>
      <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>
  );
};

export default App;