Display PDF, Images and HTML in React (iframe, react-pdf)

Web Engineer

To preview a local image, PDF or HTML file that the user picks in a React app, take the File from <input type="file">, turn it into a URL with URL.createObjectURL(), and pass it to <img> for images, <iframe>/<object> (or react-pdf) for PDFs, and a sandboxed <iframe srcdoc> for HTML. This post walks through each file type with code that was actually built and tested with React 19, Vite and TypeScript.

Updated December 2026: We replaced the deprecated create-react-app with Vite and rewrote the code in TypeScript using createObjectURL/revokeObjectURL. We also added a comparison of the ways to embed a PDF, the setup for react-pdf 11 (pdfjs-dist 6) including the cMap setting needed for Japanese and other CJK PDFs, and an explanation of sandbox for displaying uploaded HTML safely.

Quick reference: how to display each file type

FileElement / libraryWhat you passWatch out for
Image (png/jpg/webp/svg, etc.)<img>blob: URLRelease the URL with revokeObjectURL when you are done
PDF (quick display)<iframe> / <object> / <embed>blob: URLRelies on the browser's built-in PDF viewer; behavior on mobile depends on the device
PDF (full control over look and controls)react-pdf (PDF.js)The File itselfWorker setup is required; CJK PDFs may need cMaps served
HTML<iframe srcDoc sandbox>The HTML as a stringWithout sandbox, scripts in the uploaded HTML can manipulate the parent page

Setting up the project (Vite + React 19)

The first version of this post (2023) used create-react-app, but on February 14, 2025 the React team announced the deprecation of Create React App. For new projects they recommend a framework such as Next.js or React Router, or a build tool such as Vite, Parcel or Rsbuild. Since this sample is a single-page app, we use Vite.

npm create vite@latest file-viewer -- --template react-ts
cd file-viewer
npm install
npm run dev

These are the versions installed when we ran it on December 2, 2026. All code below passes npm run build (tsc -b && vite build) with this combination.

PackageVersion
create-vite9.4.0
vite8.4.1
react / react-dom19.3.1
typescript7.0.2 (the template specifies ~7.0.2)
react-pdf11.1.0 (depends on pdfjs-dist 6.5.438)

For reference, this is the start page from the first version, when the project was created with create-react-app.

Default start page after running create-react-app
The page that opens after create-react-app (recorded in 2023)

Shared code: a hook that turns a File into a URL

The first version used FileReader.readAsDataURL() to convert the file to a base64 string and keep it in state. That works, but base64 is about 4/3 the size of the original data, so a PDF of tens of megabytes means holding a huge string in state. Creating a blob: URL with URL.createObjectURL() is easier to work with.

A URL you create stays in memory until you release it explicitly, so call URL.revokeObjectURL() when the file changes and when the component unmounts. Putting this in the useEffect cleanup makes it hard to forget.

import { useEffect, useState } from "react";

// Create a blob: URL from a File and release it when the file changes or on unmount
export function useObjectUrl(file: File | null): string | null {
  const [url, setUrl] = useState<string | null>(null);

  useEffect(() => {
    if (!file) {
      setUrl(null);
      return;
    }
    const objectUrl = URL.createObjectURL(file);
    setUrl(objectUrl);
    return () => URL.revokeObjectURL(objectUrl);
  }, [file]);

  return url;
}

In development, StrictMode runs effects as "run, clean up, run again". That causes no problem here: the cleanup releases the old URL and a new one is created.

Uploading and displaying a local image

For images, just pass the blob: URL to the src of <img>. The component below accepts both images and PDFs and switches on file.type (the MIME type). The PdfEmbed component for PDFs is built in the next section.

import { useState, type ChangeEvent } from "react";
import { useObjectUrl } from "../hooks/useObjectUrl";
import { PdfEmbed } from "./PdfEmbed";

export function FileViewer() {
  const [file, setFile] = useState<File | null>(null);
  const url = useObjectUrl(file);

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setFile(e.target.files?.[0] ?? null);
  };

  return (
    <div>
      <input
        type="file"
        accept="image/*,application/pdf"
        onChange={handleChange}
      />

      {file && url && file.type.startsWith("image/") && (
        <img src={url} alt={file.name} style={{ maxWidth: "100%" }} />
      )}

      {file && url && file.type === "application/pdf" && (
        <PdfEmbed url={url} fileName={file.name} />
      )}
    </div>
  );
}

The accept attribute only filters the file picker; users can still choose other file types. That is why the display side checks file.type as well.

Image upload preview screen
Screen after uploading an image (sample from the first version) (UI labels translated to English)

Embedding a PDF with iframe, object or embed

PDFs can also be displayed by passing a blob: URL. What actually renders the file is the browser's built-in PDF viewer, not React, so the toolbar and features differ between browsers. There are three elements you can use:

ElementSyntaxFallback when the PDF can't be shownBest for
<iframe><iframe src={url} title="…" />NoneThe most straightforward option; a title also helps accessibility
<object><object data={url} type="application/pdf">…</object>Its child content is shownShowing a download link where PDFs aren't supported
<embed><embed src={url} type="application/pdf" />NoneWhat the first version used; little reason to choose it today

With any of these elements, whether the PDF displays is up to the browser. Desktop Chrome, Edge, Firefox and Safari have built-in viewers, but on mobile the result varies with the OS and browser version: the embedded area may stay blank, the file may be downloaded or handed to another app, or zooming and scrolling may be awkward. Chrome for Android reportedly gained a built-in PDF viewer in 2025 (Android Authority), but check embedded behavior on real devices.

You can check whether the browser can display PDFs inline with navigator.pdfViewerEnabled. Combined with the fallback content of <object>, this lets you show a download link where the PDF can't be displayed.

type Props = { url: string; fileName: string };

// Show the PDF in the browser's built-in viewer; fall back to a link where unavailable
export function PdfEmbed({ url, fileName }: Props) {
  if (!navigator.pdfViewerEnabled) {
    return (
      <a href={url} download={fileName}>
        Download {fileName}
      </a>
    );
  }

  return (
    <object data={url} type="application/pdf" width="100%" height="600">
      <a href={url} download={fileName}>
        Download {fileName}
      </a>
    </object>
  );
}
PDF upload preview screen
Screen after uploading a PDF (the embed version from the first post; the toolbar belongs to the browser's built-in viewer) (UI labels translated to English)

Do not add sandbox to an <iframe> that shows a PDF. According to MDN, the sandbox attribute can prevent the browser's built-in PDF viewer from loading, even with allow-scripts and similar values. This is the opposite of the HTML case below, so keep the two apart.

If you want the PDF to look the same on phones, or want to build your own page navigation and zoom UI, use react-pdf, described next.

Displaying a PDF with react-pdf (React 19, Vite)

react-pdf (wojtekmaj/react-pdf) is a React component that renders PDFs to <canvas> with Mozilla's PDF.js (npm package pdfjs-dist). It does not use the browser's built-in viewer, so it looks the same on mobile. It is not the same as @react-pdf/renderer, which creates PDFs, so double-check the package name when installing.

ItemAs of December 2026 (react-pdf 11.1.0)
Supported ReactReact 19 or later (peerDependencies ^19.0.0)
Bundled pdfjs-dist6.5.438 (pinned)
Node.js22.13.0 or later
Main change in v11Document, Page and others use Suspense and Error Boundaries by default (suspense={false} restores the old loading/error props)
Older browsersChrome 125 and Safari 18 (iOS 18) are supported through the PDF.js legacy build

Installation

react-error-boundary is used to match the README examples; you don't need it if you have your own Error Boundary. vite-plugin-static-copy copies cMaps and other assets (see below) into the build output.

npm install react-pdf react-error-boundary
npm install -D vite-plugin-static-copy

Worker and Vite configuration

react-pdf parses PDFs in a Web Worker, so setting pdfjs.GlobalWorkerOptions.workerSrc is required. The README points out two things:

  • The worker must be exactly the same version as the pdfjs-dist that react-pdf uses (if you install pdfjs-dist yourself, match the version)
  • Set workerSrc in the same file where you use <Document>, not in main.tsx or similar (depending on module evaluation order, it can be overwritten by the default value)

In Vite, writing new URL("pdfjs-dist/build/pdf.worker.min.mjs", import.meta.url) makes the build emit the worker file to dist/assets/. Also add a vite.config.ts setting that copies the cMaps (needed for CJK PDFs), standard fonts and image decoders such as JPEG 2000 (wasm) to the root of dist.

import path from "node:path";
import { createRequire } from "node:module";
import react from "@vitejs/plugin-react";
import { defineConfig, normalizePath } from "vite";
import { viteStaticCopy } from "vite-plugin-static-copy";

const require = createRequire(import.meta.url);
const pdfjsDistPath = path.dirname(require.resolve("pdfjs-dist/package.json"));

export default defineConfig({
  plugins: [
    react(),
    viteStaticCopy({
      targets: [
        { src: normalizePath(path.join(pdfjsDistPath, "cmaps")), dest: "cmaps", rename: { stripBase: true } },
        { src: normalizePath(path.join(pdfjsDistPath, "standard_fonts")), dest: "standard_fonts", rename: { stripBase: true } },
        { src: normalizePath(path.join(pdfjsDistPath, "wasm")), dest: "wasm", rename: { stripBase: true } },
      ],
    }),
  ],
});

The PDF viewer component

A minimal viewer with file selection, page navigation, and loading and error states. You can pass a File object straight to react-pdf's file prop, so createObjectURL isn't needed.

import { Suspense, useState, type ChangeEvent } from "react";
import { ErrorBoundary } from "react-error-boundary";
import { Document, Page, pdfjs } from "react-pdf";
import "react-pdf/dist/Page/AnnotationLayer.css";
import "react-pdf/dist/Page/TextLayer.css";

// Set the worker in this file, where <Document> is used
pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  "pdfjs-dist/build/pdf.worker.min.mjs",
  import.meta.url,
).toString();

// Defined outside the component (so it isn't a new object on every render)
const options = {
  cMapUrl: "/cmaps/",
  standardFontDataUrl: "/standard_fonts/",
  wasmUrl: "/wasm/",
};

export function PdfViewer() {
  const [file, setFile] = useState<File | null>(null);
  const [numPages, setNumPages] = useState<number>(0);
  const [pageNumber, setPageNumber] = useState<number>(1);

  const handleChange = (e: ChangeEvent<HTMLInputElement>) => {
    setFile(e.target.files?.[0] ?? null);
    setPageNumber(1);
  };

  return (
    <div>
      <input type="file" accept="application/pdf,.pdf" onChange={handleChange} />

      {file && (
        <ErrorBoundary key={`${file.name}-${file.lastModified}`} fallback={<p>Could not load the PDF.</p>}>
          <Suspense fallback={<p>Loading…</p>}>
            <Document
              file={file}
              options={options}
              onLoadSuccess={({ numPages }) => setNumPages(numPages)}
            >
              <Page pageNumber={pageNumber} width={600} />
            </Document>
          </Suspense>
        </ErrorBoundary>
      )}

      {numPages > 0 && (
        <div>
          <button
            type="button"
            disabled={pageNumber <= 1}
            onClick={() => setPageNumber((p) => p - 1)}
          >
            Previous
          </button>
          <span>
            {pageNumber} / {numPages}
          </span>
          <button
            type="button"
            disabled={pageNumber >= numPages}
            onClick={() => setPageNumber((p) => p + 1)}
          >
            Next
          </button>
        </div>
      )}
    </div>
  );
}

options is defined outside the component because creating it inside would produce a different value on every render and trigger reloads. The Error Boundary's key includes the file name and modification time so that its error state resets when the user picks a different file.

Japanese (CJK) PDFs may need cMapUrl

PDFs that don't embed their fonts and instead reference standard Japanese CID fonts (such as HeiseiMin-W3) can't render their text without cMaps. The same applies to other CJK (Chinese, Japanese, Korean) PDFs. We created a test PDF of this kind and loaded it in the viewer above:

Japanese PDF rendered with react-pdf when cMapUrl is set
With cMapUrl set, the Japanese text renders (Chromium, checked December 2, 2026)

When we removed cMapUrl from options and loaded the same PDF, the page stayed blank, the text layer was empty, and the console showed these warnings:

Warning: loadFont - translateFont failed: "UnknownErrorException: Ensure that the `cMapUrl` API parameter is provided.".
Warning: Error during font loading: Ensure that the `cMapUrl` API parameter is provided.

PDFs with embedded fonts are not affected, but you can't control what users upload, so it's safest to configure this from the start. The README also describes pointing to a CDN (https://unpkg.com/pdfjs-dist@${pdfjs.version}/cmaps/) instead of copying the cMaps.

Using react-pdf in Next.js

PDF.js only runs in the browser, so in Next.js load the component that uses react-pdf without SSR (in the App Router, use next/dynamic with ssr: false inside a 'use client' component). For type-safe routing in Next.js, see "Typing useRouter with pathpida in Next.js".

Uploading and displaying a local HTML file

HTML can't be shown with <img> or <embed>, so use <iframe>. The thing to watch is any <script> inside the uploaded HTML.

Without sandbox, the HTML can manipulate the parent page

A blob: URL has the same origin as the page that created it, and srcdoc also runs in the parent's origin. So if you display the file without sandbox, scripts in the uploaded HTML can reach parent.document, cookies and localStorage. We tested an HTML file whose script rewrites parent.document.title with different display methods (Chromium):

Display methodCould it change the parent page's title?
<iframe src={blob URL}> (no sandbox)Yes
<iframe srcDoc={html}> (no sandbox)Yes
data: URL (the first version's readAsDataURL approach)No (it gets an opaque origin)
blob URL / srcdoc with sandbox="allow-scripts"No

The first version's code used a data: URL, so it happened to be isolated from the parent, but switching to createObjectURL removes that protection. Always add the sandbox attribute when displaying uploaded HTML.

Code: srcdoc + sandbox

Read the HTML as a string with File.text() and pass it to srcDoc. sandbox="" (no value) is the strictest setting: it blocks scripts, form submission, popups and more.

import { useState, type ChangeEvent } from "react";

export function HtmlPreview() {
  const [html, setHtml] = useState<string>("");

  const handleChange = async (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    setHtml(file ? await file.text() : "");
  };

  return (
    <div>
      <input type="file" accept=".html,text/html" onChange={handleChange} />
      {html && (
        <iframe
          srcDoc={html}
          sandbox=""
          title="Uploaded HTML"
          width="100%"
          height="400"
        />
      )}
    </div>
  );
}

When we loaded an HTML file containing a script with this code, only the content was shown, the console reported Blocked script execution in 'about:srcdoc' because the document's frame is sandboxed and the 'allow-scripts' permission is not set., and the script did not run.

If you also want JavaScript in the preview to run, use sandbox="allow-scripts". But if you set allow-scripts and allow-same-origin together, scripts inside the iframe can remove the sandbox attribute themselves, and MDN warns against combining them.

The sample HTML from the first version, and the result:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
	"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
	<head>
		<title>Sample HTML document</title>
	</head>
	<body>
		<p>Hello, World!</p>
	</body>
</html>
HTML upload preview screen
Screen after uploading an HTML file (sample from the first version) (UI labels translated to English)

App.tsx combining all three

import { FileViewer } from "./components/FileViewer";
import { HtmlPreview } from "./components/HtmlPreview";
import { PdfViewer } from "./components/PdfViewer";

export default function App() {
  return (
    <main>
      <h2>Image / PDF (browser built-in)</h2>
      <FileViewer />
      <h2>HTML (sandboxed iframe)</h2>
      <HtmlPreview />
      <h2>PDF (react-pdf)</h2>
      <PdfViewer />
    </main>
  );
}

We ran this project with npm run build → npx vite preview, selected an image (SVG), an HTML file and a Japanese PDF in headless Chromium, and confirmed that the image displays from a blob: URL, the HTML displays inside the sandbox with its script blocked, and the PDF renders with react-pdf.

Common problems

  • Selecting the same file again does nothing: the value doesn't change, so onChange doesn't fire. Reset the input with e.target.value = "" at the end of the handler.
  • react-pdf throws "worker" errors: check that workerSrc is set in the same file as <Document> and that there aren't multiple versions of pdfjs-dist installed (npm ls pdfjs-dist).
  • react-pdf doesn't show Japanese/CJK text: set cMapUrl in options and check that the cMaps are actually served (that /cmaps/ is reachable).
  • The build warns "Some chunks are larger than 500 kB": with react-pdf, the main JS bundle in this setup was about 870 kB. Lazy-loading the PDF viewer with React.lazy reduces the impact on initial load.
  • It doesn't work on static hosting such as Render: check that the whole dist folder is deployed (including cmaps, standard_fonts and wasm). If you run into trouble deploying to Render, see "Render deploy errors and how to fix them".

Summary

  • To preview local files, create a URL with URL.createObjectURL() and call revokeObjectURL() in the useEffect cleanup
  • Use <img> for images; for PDFs, use <iframe> for simplicity or <object> for a fallback, and react-pdf for consistent rendering
  • react-pdf 11 requires React 19. Set the worker in the same file and specify cMapUrl for CJK PDFs
  • Display uploaded HTML with srcDoc + sandbox, and never combine allow-scripts with allow-same-origin

References

Title and URL copied