PhotoCapture
Take a photo with the camera or pick a file, crop it, and get a File back. A composition of Camera, FileTrigger and ImageCropper, driven by a small step reducer.
PhotoCapture is how a photo gets into a form: a profile picture, a badge photo, a scanned document. The visitor takes one with the camera or picks a file, crops it, and presses Use photo. onChange then receives the cropped File, and not before. Nothing is uploaded: the File is yours to send.
import { PhotoCapture } from '@42-central/ui-react/photo-capture';
<PhotoCapture shape="circle" output={{ size: 512 }} onChange={(file) => setAvatar(file)} />It's built from bricks you can use on their own. Camera takes the photo, FileTrigger picks a file or opens a phone's camera app, and ImageCropper crops it. usePhotoCapture, a small step reducer, decides which of them is on screen. Everything the flow does, the camera turning off after a shot, the recovery steps after a refusal, the keyboard crop, comes from those bricks.
Playground
Component
Dir
Presets
Props
Code
<Component />Full prop browser
Basic
Take photo opens the camera; Choose a file opens the file picker. They sit side by side at the same weight, because a camera isn't always there or allowed. The photo, taken or picked, goes straight to the cropper: taking and cropping are one step, with no review screen in between. Retake goes back to the camera; Use photo hands over the File.
Add a photo
Nothing leaves this page until you choose Use photo.
Code
const [photo, setPhoto] = useState<File | null>(null);
<PhotoCapture onChange={setPhoto} />The camera stays off until Take photo, even on a site where it's already allowed. It turns off again as soon as the photo is taken, when a file is picked instead, and when PhotoCapture unmounts.
The camera: live or native
camera picks how the photo is taken:
camera | What happens |
|---|---|
"live" | The camera in the page: a viewfinder with a guide, a shutter, a switch between cameras. |
"native" | The phone's own camera app, through a file input with capture. No viewfinder in the page. |
"auto" (default) | native under a coarse pointer (a phone, a tablet), live otherwise. |
The native camera app is the better camera on a phone. It focuses, exposes and stabilizes, and it never asks the browser for permission. In native mode, the first step shows two pickers: Take photo, with capture, and Choose from library, without it. A single picker isn't enough: Android 14 and 15 hide the camera from a picker that has no capture, and a picker with it hides the library. Desktop browsers ignore capture, so on a desktop both open the file picker.
Add a photo
Nothing leaves this page until you choose Use photo.
Code
<PhotoCapture camera="native" onChange={setPhoto} />Recipes
There are no presets: each use is a handful of props.
Avatar
The front camera, a face guide, a circle crop, and a 512px WebP. A circle exports a square image; mask it where you show it, as Avatar does.
Add a photo
Nothing leaves this page until you choose Use photo.
Code
<PhotoCapture
facing="user"
shape="circle"
output={{ type: 'image/webp', quality: 0.85, size: 512 }}
onChange={setAvatar}
/>ID or badge photo
A portrait ratio, and a rectangle guide in the same ratio, so the framing in the camera is the crop that comes out.
Add a photo
Nothing leaves this page until you choose Use photo.
Code
<PhotoCapture facing="user" ratio="3/4" shape="rectangle" output={{ size: 1200 }} onChange={setBadge} />Document
The back camera at 4K, a free crop to trim the edges, and a large export, so the text stays readable.
Add a photo
Nothing leaves this page until you choose Use photo.
Code
<PhotoCapture
facing="environment"
resolution={{ width: 3840, height: 2160 }}
output={{ type: 'image/jpeg', quality: 0.92, size: 3000 }}
onChange={setScan}
/>Any image
A cover or a post: a 16/9 crop, at most 1920px wide.
Add a photo
Nothing leaves this page until you choose Use photo.
Code
<PhotoCapture ratio="16/9" output={{ size: 1920 }} onChange={setCover} />In a modal or a drawer
PhotoCapture renders inline; whether it opens in an overlay is your call. The usual layout is a Modal on a desktop and a bottom-sheet Drawer on a phone, with the flow as their content. Close it from onChange:
Code
const phone = useMediaQuery('(width < 40rem)');
const capture = (
<PhotoCapture
shape="circle"
output={{ size: 512 }}
onChange={(file) => {
setAvatar(file);
setOpen(false);
}}
/>
);
<Button onClick={() => setOpen(true)}>Change photo</Button>
{phone ? (
<Drawer open={open} onOpenChange={setOpen} placement="bottom" withGrabber title="Profile photo">
{capture}
</Drawer>
) : (
<Modal open={open} onOpenChange={setOpen} title="Profile photo">
{capture}
</Modal>
)}Modal and Drawer unmount their content once closed, and PhotoCapture turns the camera off when it unmounts. Closing the overlay, by Escape, the backdrop or a swipe, turns the camera off with it. Each opening starts over at the first step.
Output
onChange receives a File named photo.jpg, or for whatever type the browser actually encoded:
output.type,image/jpegby default. A browser that can't encode the type you ask for (Safari has no WebP encoder) falls back to PNG, and the File'stypeand extension say so.output.quality, 0–1,0.9by default, for JPEG and WebP.output.size, the longest side in px. A larger crop is scaled down to fit; a smaller one is kept as is, never scaled up.
With a ratio, or a circle, the File holds that ratio to the pixel: a 512px avatar is 512 × 512.
A selfie is saved the right way round, as others see you, even though the camera's preview is mirrored like a mirror. Pass mirror to save it as the preview shows it.
Composable parts
<PhotoCapture> is one arrangement of the parts. They read a usePhotoCapture() of your own through PhotoCapture.Root, so you can lay the flow out differently, swap a button, or leave a step out:
Add a photo
Nothing leaves this page until you choose Use photo.
Steps:
Code
const flow = usePhotoCapture({ camera: 'live', ratio: '1/1', onChange: setPhoto });
<PhotoCapture.Root flow={flow}>
<PhotoCapture.Source>
<PhotoCapture.Take variant="outline" />
<PhotoCapture.File variant="outline" />
</PhotoCapture.Source>
<PhotoCapture.Live />
<PhotoCapture.Crop>
<PhotoCapture.Retake variant="subtle" />
<PhotoCapture.Confirm />
</PhotoCapture.Crop>
</PhotoCapture.Root>usePhotoCapture returns plain state and handlers:
step("source","live"or"crop"),mode(autoresolved for this device),photo,origin("camera","native"or"file"),busyandfailed.camera: theuseCamera()result behind the viewfinder, mounted withlazyso it only turns on withopen().open()opens the camera.take(file)is the shutter's photo.pick(files, origin)takes a picked file.retake()goes back to the camera.confirm(crop)exports through the cropper'sgetCroppedImageand callsonChange.reset()goes back to the first step with the camera off.
The steps themselves are a pure reducer, reducePhotoCapture, exported with its state and event types. An event that doesn't apply to the current step, such as a late shutter after a file was picked, or a second Use photo while the first is exporting, changes nothing.
| Step | Shows | Leaves on |
|---|---|---|
source | Take photo and the file picker, or in native mode the camera app and the library. | Take photo → live. A file, or a native photo → crop. |
live | The camera, its status panels and the file picker. | The shutter → crop. A file → crop, the camera off. |
crop | The photo in the cropper, Retake, Use photo. | Retake → live (or the picker again). Use photo → onChange, then source. |
Privacy
- Nothing leaves the page. The kit never uploads:
onChangegets a File, and the request is yours to make. - Nothing before Use photo. Taking, retaking and cropping emit nothing.
- The camera is on only in the live step. It waits for Take photo, even when the site is already allowed. It turns off when the photo is taken, when a file is picked instead, when the page is hidden, and when
PhotoCaptureunmounts. - No location, no EXIF. The File is drawn onto a canvas and encoded again, which writes no metadata. A photo picked from a phone loses its GPS position, its device and its date. Browsers apply its EXIF orientation as they draw it (
image-orientation: from-imageis the default), so a portrait photo comes out upright, without the orientation tag it no longer needs. - No storage. Nothing is kept in
localStorageor anywhere else.
Accessibility
- Keyboard-only, start to finish. Every control is a native button. After Take photo, focus moves to the shutter once the camera is live: Space takes the photo. Focus then moves to Use photo: Enter uses it. In between, the crop moves with the arrow keys, resizes with Alt and the arrows, and zooms with + and -.
- Focus follows the steps. Retake puts it back on the shutter, once the camera is live again. After Use photo, it returns to the first choice. It never lands on the page body because a button disappeared.
- Every step is announced. A polite live region says "Photo ready to crop" and "Photo added". The camera announces its own states ("Starting the camera", "Camera ready") and its failures are alerts.
- The file picker is always there, at the same weight as the camera: beside the camera's buttons, beside the shutter, and inside every camera panel (asking, refused, busy, no camera). Someone who can't or won't use a camera never hits a dead end.
- Every control is named through
translations, including the camera's and the cropper's. - Reduced motion. The shutter's flash becomes a still outline, and the cropper's fades are off.
- Right to left. Logical properties throughout; see below.
Internationalization
One translations map covers everything PhotoCapture shows: its own strings, the camera's and the cropper's. Under a right-to-left locale the buttons, the camera's badge and the crop controls mirror; the photo itself never does.
أضف صورة
لا يغادر شيء هذه الصفحة قبل أن تختار «استخدام الصورة».
Code
<IntlProvider locale="ar-EG">
<div dir="rtl" lang="ar">
<PhotoCapture shape="circle" translations={arabic} />
</div>
</IntlProvider>PhotoCapture's own keys:
| Key | Default |
|---|---|
sourceTitle | "Add a photo" |
sourceBody | "Nothing leaves this page until you choose Use photo." |
take | "Take photo" |
file | "Choose a file" |
library | "Choose from library", in native mode |
retake | "Retake" |
another | "Choose another", the retake for a picked file |
confirm | "Use photo" |
failed | "The photo couldn't be prepared. Try again, or choose another." |
announceCrop / announceDone | "Photo ready to crop" / "Photo added" |
Icons
icons replaces any of the defaults, per slot: take, file, retake and confirm, plus the camera's shutter, flip, start, retry and off. Your icons are drawn as given: add className={iconStroke} (from @42/ui-react) for the kit's 1.5px line.
<PhotoCapture icons={{ take: <Aperture className={iconStroke} />, confirm: <Upload className={iconStroke} /> }} />API
Prop
Type
PhotoCapture.Root takes flow (a usePhotoCapture() result) instead of onChange, camera, facing, ratio, resolution, mirror and output, which go to the hook, and its own children.
Parts
| Part | Renders | Notes |
|---|---|---|
PhotoCapture.Root | <div> | The flow, shape, accept, translations, icons, color. The polite live region. Takes asChild. |
PhotoCapture.Source | <div> | The first step. Its children replace Take and File. |
PhotoCapture.Live | Camera.Root | The live step: viewfinder, guide, panels, shutter, switch, picker, file. classNames.viewfinder, classNames.controls. |
PhotoCapture.Crop | ImageCropper.Root | The crop step. Its children replace Retake and Use photo, and must keep Confirm. |
PhotoCapture.Take | A Button, or a FileTrigger in native mode | Takes Button props; children replace the label. |
PhotoCapture.File | A FileTrigger | "Choose a file", or "Choose from library" in native mode. |
PhotoCapture.Retake | A Button or a FileTrigger | By the photo's origin: the camera, the camera app, or another file. |
PhotoCapture.Confirm | A Button | Use photo. Inside Crop. |
usePhotoCaptureContext() returns the flow, the translations and the icons, for a part of your own inside PhotoCapture.Root.
Testing
testId lands on the root, which also carries data-step and data-mode. Find the buttons by role and name: "Take photo", "Choose a file", "Retake", "Use photo". jsdom has no camera, no canvas and no layout:
- The camera. Give jsdom a fake
navigator.mediaDevices, as on the Camera page, then fireloadeddataon the video ("Camera preview") for the first frame. - A file. Fire
changeon the hidden input right after the picker's button, with{ target: { files: [file] } }. - Use photo. Ark's
getCroppedImageneeds a laid-out image and a canvas, so stub it: mock@ark-ui/react/image-cropper'suseImageCropperContextto return the real API with agetCroppedImagethat resolves aBlob.
vi.mock('@ark-ui/react/image-cropper', async (importOriginal) => {
const original = await importOriginal<typeof import('@ark-ui/react/image-cropper')>();
return {
...original,
useImageCropperContext: () => ({
...original.useImageCropperContext(),
getCroppedImage: async () => new Blob(['crop'], { type: 'image/jpeg' }),
}),
};
});
render(<PhotoCapture onChange={onChange} />);
const choose = screen.getByRole('button', { name: 'Choose a file' });
fireEvent.change(choose.nextElementSibling!, { target: { files: [photo] } });
await user.click(screen.getByRole('button', { name: 'Use photo' }));
expect(onChange).toHaveBeenCalledWith(expect.any(File));In a real browser, Chromium's --use-fake-device-for-media-stream and --use-fake-ui-for-media-stream flags give Playwright a camera that's always allowed, and the filechooser event's setFiles() picks a file.
Changelog
- #464
No computed-style read on mount in production: the RTL direction check runs in development only
- #364
New
PhotoCapture: take or pick a photo, crop it, and get aFileinonChangeon "Use photo";shape,ratio,output={{ type, quality, size }}, and the phone's camera app on touch devices (camera="auto")
Camera
Take a photo in the page. A live viewfinder with a framing guide, a shutter, a camera switch, and a panel for every state, from the first permission prompt to the steps that undo a refusal. The photo comes back as a File.
Breadcrumb
A trail of links showing the current page's place in a hierarchy, with an auto-muted current crumb and router-link support.