Skip to content

Calling methods on the components - React

You can call methods on the components by using a reference.

Use the useRef hook to obtain a reference to the element;

tsx
const pdfApplication = useRef<HTMLPdfApplicationELement>(null);

return (
    <>
        <PdfApplication ref={pdfApplication} />
    </>
);

You can then call a method on the reference. In this example we call the getDocuments method of the PdfApplication component.

ts
pdfApplication.current.getDocuments();

Make sure to wrap this call in a useEffect and verify that the pdfApplication has a value

ts
useEffect(() => {
    if (pdfApplication.current) {
        pdfApplication.current.getDocuments().then((documents) => {
            setDocuments(documents);
        });
    }
}, [pdfApplication]);

See below for a full example.

Screenshot

Screenshot op calling-methods

Code

tsx
import {
  IPdfDocument,
  PdfApplication,
  defineCustomElements,
} from "@tallcomponents/unopdf-react";

import { useEffect, useRef, useState } from "react";

defineCustomElements();

// Note: this example uses Vite and retrieves the keys from the environment.
// This should not be used in production.
// See the authentication section in the usage guide for more information.

const publickey = import.meta.env.VITE_PUBLIC_KEY;
const privatekey = import.meta.env.VITE_PRIVATE_KEY;

function App() {
  const [documents, setDocuments] = useState<IPdfDocument[]>();
  const pdfApplication = useRef<HTMLPdfApplicationElement>(null);

  useEffect(() => {
    if (pdfApplication.current) {
      pdfApplication.current.getDocuments().then((documents) => {
        setDocuments(documents);
      });
    }
  }, []);

  return (
    <>
      <h1>UnoPdf Example: Calling methods in React</h1>

      <PdfApplication
        ref={pdfApplication}
        publickey={publickey}
        privatekey={privatekey}
      />

      {documents && (
        <>
          <h2>Documents in storage</h2>
          <ul>
            {documents.map((document) => (
              <li key={document.id}>{document.originalFileName}</li>
            ))}
          </ul>
        </>
      )}
    </>
  );
}

export default App;

Running the example

  • Download the react - Calling methods on the components project
  • Unzip the file to a directory react-calling-methods.
    shell
    unzip react-calling-methods.zip -d react-calling-methods
  • Open a terminal and go to that directory
    shell
    cd react-calling-methods
  • Install dependencies
    shell
    npm install
    shell
    yarn
  • Start the project
    shell
    npm run start
    shell
    yarn start