React avatar capture
Build avatar capture with a React webcam.
Capture profile photos, convert them to Files, and upload them with `FormData` using the `Webcam` component or the lower-level `useWebcam()` hook.
Upload a captured avatar
import { useRef } from 'react';
import { Webcam, type WebcamHandle } from 'react-webcam-kit';
export function AvatarCapture() {
const webcamRef = useRef<WebcamHandle>(null);
async function saveAvatar() {
const blob = await webcamRef.current?.getScreenshotBlob({
format: 'image/jpeg',
quality: 0.9,
width: 512,
height: 512,
});
if (!blob) return;
const form = new FormData();
form.set('avatar', new File([blob], 'avatar.jpg', { type: blob.type }));
await fetch('/api/avatar', {
method: 'POST',
body: form,
});
}
return (
<>
<Webcam ref={webcamRef} audio={false} mirrored screenshotFormat="image/jpeg" />
<button type="button" onClick={() => void saveAvatar()}>Save avatar</button>
</>
);
}
Good production defaults
- Use JPEG for profile photos unless transparency is required.
- Handle `null` capture results for blocked canvas or not-ready video states.
- Stop streams when users close the avatar modal.
- Use `mirrored` for front-facing preview when it matches user expectations.