useObjectUrl
A URL for a picked or dropped file that's safe to put in an img, video or object, revoked for you, and never one that lets an uploaded file run as your app.
useObjectUrl turns a Blob or a File into a URL your page can load, and revokes it when the file changes or the component unmounts. Reach for it whenever you show a file the user picked or dropped. It's the one way the kit itself does it: FileItem and FileUpload thumbnails, FilePreview, ImageCropper and PhotoCapture all go through it.
import { useObjectUrl } from '@42-central/ui-react';
const url = useObjectUrl(file);
<img src={url} alt="" />Never URL.createObjectURL(file) for an uploaded file. An object URL has your app's origin, so "Open image in new tab" on an uploaded .svg or .html runs its script as your app. useObjectUrl shows a file only under a type the kit allows:
| The source | What you get |
|---|---|
| PDF, raster image, common video or audio, plain text | An object URL for the Blob re-wrapped under that type, never the type it claims |
SVG, up to SVG_DATA_URL_LIMIT (5 MB) | A data: URL, whose document has an opaque origin |
| Anything else: HTML, XML, an unknown or "binary" type | undefined, so nothing is shown |
| A string | Passed through untouched |
The full rules, and why, are in Files › useObjectUrl.
Usage
Pick any file, or try the two samples. The SVG comes back as a data: URL; the HTML file gets no URL at all.
Code
const [file, setFile] = useState<File>();
const url = useObjectUrl(file);
<FileTrigger onSelect={([first]) => setFile(first)}>Choose a file</FileTrigger>
{url ? <img src={url} alt="" /> : <p>Nothing to show</p>}The URL is made in an effect, never during render, so Strict Mode's double render leaks nothing. That makes it undefined on the server and for a Blob's first render (an SVG's until it's read): render a placeholder for that frame. After the source changes, the hook never hands out the previous, already revoked URL.
API
Prop
Type
Returns a string, or undefined while the URL is being made and for a Blob it won't show.
useFileQueue
An upload queue that runs the state machine and leaves the network to you. Concurrency, cancel, retry, batches, an aggregate progress and one screen-reader summary per upload, wired straight into FileItem and FileUpload.
useTheme
Reads and sets the persisted light, dark or system choice, keeping data-theme on the html element in sync across tabs and with the OS.