Capture HTML to PNG in React
Integrate SnapDOM with React refs, display image previews with object URL cleanup, and reuse the capture logic across components.
Attach a useRef to the element you want to capture, install @zumer/snapdom, and call snapdom.toPng(ref.current) from a button handler. SnapDOM returns the HTMLImageElement ready to append.
1. Install
npm install @zumer/snapdom@latest
SnapDOM ships an ES module with no runtime dependencies. For server-rendered apps, follow the Next.js guide to keep capture in the browser.
2. Minimal capture component
import { useRef } from 'react'; import { snapdom } from '@zumer/snapdom'; export function CaptureCard() { const cardRef = useRef(null); const handleCapture = async () => { if (!cardRef.current) return; const img = await snapdom.toPng(cardRef.current, { scale: 2 }); document.body.appendChild(img); }; return ( <div> <div ref={cardRef} className="card"> <h3>Hello SnapDOM</h3> <p>This whole div will be captured.</p> </div> <button onClick={handleCapture}>Capture</button> </div> ); }
The button appends the captured PNG to the document.
Try it live
This plain HTML demo runs the same capture call on a rendered card. In React, the component ref supplies that DOM element.
Hello SnapDOM
This whole div will be captured.
3. Download instead of appending
Use download() to save the captured card as a file:
const handleDownload = async () => { if (!cardRef.current) return; const result = await snapdom(cardRef.current); await result.download({ format: 'png', filename: 'card' }); };
4. Keep the captured image in state
If you want to render a preview inside your component, store the image as an object URL using toBlob + URL.createObjectURL:
import { useEffect, useRef, useState } from 'react';
import { snapdom } from '@zumer/snapdom';
export function CapturePreview() {
const cardRef = useRef(null);
const [previewUrl, setPreviewUrl] = useState(null);
useEffect(() => () => {
if (previewUrl) URL.revokeObjectURL(previewUrl);
}, [previewUrl]);
const handleCapture = async () => {
if (!cardRef.current) return;
const blob = await snapdom.toBlob(cardRef.current, { format: 'png' });
setPreviewUrl(URL.createObjectURL(blob));
};
return (
<>
<div ref={cardRef}>…</div>
<button onClick={handleCapture}>Capture</button>
{previewUrl && <img src={previewUrl} alt="preview" />}
</>
);
}
The effect releases each object URL when the preview changes or the component unmounts.
5. Reusable React hook
If you call SnapDOM from many components, extract a small hook:
// useSnapdom.js import { useCallback, useRef } from 'react'; import { snapdom } from '@zumer/snapdom'; export function useSnapdom(options = {}) { const ref = useRef(null); const capture = useCallback(async (format = 'png') => { if (!ref.current) return null; const result = await snapdom(ref.current, options); return result.to(format); }, [options]); return { ref, capture }; }
Use it like this:
const { ref, capture } = useSnapdom({ scale: 2, embedFonts: true }); return ( <> <div ref={ref}>…</div> <button onClick={() => capture('png')}>Capture</button> </> );
Export a real component
For a minimal PNG download handler, use the React card download recipe. For several widgets together, use the dashboard recipe. For a file to upload, adapt the PNG Blob and FormData example after the ref’s content has finished rendering.
Common gotchas
My captured image is blank or empty
Check these conditions:
1. You called snapdom before the ref was attached. Always trigger the capture from a user event (button click) or inside useEffect after mount, never directly inside the component body.
2. The captured element has display: none or is detached from the document. SnapDOM needs a rendered element in the live DOM tree.
If the handler updates React state before capture, wait for that update to commit. Capturing immediately after a state setter can read the previous DOM. Data, chart animations, fonts and images have separate readiness checks.
Web fonts render as Times New Roman
SnapDOM defaults to embedFonts: 'auto' and embeds used web fonts when their files are accessible. Wait for application data and fonts to settle before capture if they can change the layout.
Cross-origin images don't render
SnapDOM fetches external images and inlines them as data URLs. If your CDN doesn't send Access-Control-Allow-Origin, configure a proxy with { useProxy: 'https://your-proxy.example.com/' }.
Does SnapDOM work with React 18 strict mode?
Yes. SnapDOM doesn't subscribe to React lifecycle, so the double-invocation in development strict mode doesn't affect captures triggered from event handlers.
Can I use SnapDOM in Next.js?
Yes — use a client component ('use client') and a dynamic import. See the dedicated Next.js guide.
Does SnapDOM work with React Native?
No. SnapDOM is a browser-only library — it relies on DOM APIs and SVG foreignObject that don't exist in React Native.