Repository files navigation

npm version

licenseTypeScriptReactDocs

react-webcam-pro

Universal Camera component for React.

Designed with focus on Android and iOS cameras. Works with standard webcams as well.

🚀 Live Demo

See browser compatibility.

Note: WebRTC is only supported on secure connections (HTTPS). You can test and debug from localhost in Chrome (this doesn't work in Safari).


🔀 Fork Notice

react-webcam-pro is a community-maintained fork of react-camera-pro by Purple Technology.

The original package has not been actively maintained for over 2 years, leaving many users with unresolved issues — including React 19 compatibility, styled-components warnings, and various bug fixes. Many of us personally needed these updates, so we decided to fork the project, fix the outstanding issues, and continue maintaining it for the community.

🙏 Acknowledgements

A huge thank you to the original creators and contributors of react-camera-pro:


✨ What's New

v1.2.0 — April 8, 2026

  • <CropView /> component — WhatsApp-style interactive crop after photo capture
  • Drag, resize, pinch — Cross-platform crop interactions (desktop + mobile)
  • Aspect ratio lock — Lock crop to 1:1, 16:9, 4:3, or free-form
  • Circle crop shape — Visual circular crop mask (output still rectangular)
  • Ref-controlledcropImage(), resetCrop(), getCropArea() via ref
  • Zero new dependencies — Uses native Canvas & Pointer Events APIs

👉 Full v1.2.0 release notes

v1.1.0 — April 7, 2026

  • videoConstraints prop — Control resolution, frame rate, and any MediaTrackConstraints (#52)
  • Mirrored photo capturetakePhoto({ mirror: true }) for selfie-correct photos (#74)
  • Fixed Firefox & iOS 15 crashgetCapabilities() handled gracefully with developer warning (#75, #77)
  • Interactive example app — Try all props live at react-webcam-pro.vercel.app

👉 Full v1.1.0 release notes

v1.0.0 — April 6, 2026 (Initial Release)

  • React 19 support — Works with React 16.8+, 17, 18, and 19
  • styled-components v6 support — Compatible with both v5 and v6
  • Fixed DOM warnings — No more mirrored and aspectRatio prop warnings (#48)
  • errorMessages is now truly optional (#63)
  • className and style props — Style the camera container easily (#47)
  • Fixed camera switching with videoSourceDeviceId — Device selection works correctly in environment mode (#62, #69)
  • Proper test suite — Jest + React Testing Library
  • Modern toolchain — TypeScript 5, Rollup 4

👉 Full v1.0.0 release notes · All releases →


Features

  • 📱 Mobile-friendly camera solution (tested on iOS and Android)
  • 📐 Fully responsive video element
    • Cover your container or define aspect ratio (16/9, 4/3, 1/1, ...)
  • 📸 Take photos as base64 JPEG or ImageData — with the same aspect ratio as the view
  • 🪞 Mirror captured photos with takePhoto({ mirror: true })
  • ✂️ WhatsApp-style crop with <CropView /> — drag, resize, aspect ratio lock (new in v1.2.0)
  • 🎛️ Custom video constraints via videoConstraints prop (resolution, fps, etc.)
  • 🖥️ Works with standard webcams and other video input devices
  • 🔄 Switch between user/environment cameras
  • 🔦 Torch/flashlight support
  • 🔢 Detect number of available cameras
  • 🔮 Facing camera is mirrored, environment is not
  • ⚡ Controlled via React Ref
  • 📝 Written in TypeScript

Installation

npm install react-webcam-pro

Peer dependencies:react, react-dom, and styled-components (v5 or v6).

📖 Documentation:amareshsm.github.io/react-webcam-pro
🎮 Try it live:react-webcam-pro.vercel.app


Quick Start

importReact,{useState,useRef}from"react";import{Camera}from"react-webcam-pro";constApp=()=>{constcamera=useRef(null);const[image,setImage]=useState(null);return(<div><Cameraref={camera}/><buttononClick={()=>setImage(camera.current.takePhoto())}>
Take photo
</button><imgsrc={image}alt="Taken photo"/></div>);};exportdefaultApp;

Props

PropTypeDefaultDescription
facingMode'user' | 'environment''user'Default camera facing mode
aspectRatio'cover' | number'cover'Aspect ratio of the video (e.g. 16/9, 4/3)
numberOfCamerasCallback(numberOfCameras: number) => void() => nullCalled when the number of cameras changes
videoSourceDeviceIdstringundefinedSpecific video device ID to use
videoConstraintsMediaTrackConstraintsundefinedCustom video constraints (resolution, fps, etc.) (new in v1.1.0)
errorMessagesobject (optional)See belowCustom error messages
videoReadyCallback() => void() => nullCalled when the video feed is ready
classNamestringundefinedCSS class name for the container
styleReact.CSSPropertiesundefinedInline styles for the container

Error Messages

All fields are optional. Defaults:

{noCameraAccessible: 'No camera device accessible. Please connect your camera or try a different browser.',permissionDenied: 'Permission denied. Please refresh and give camera permission.',switchCamera: 'It is not possible to switch camera to different one because there is only one video device accessible.',canvas: 'Canvas is not supported.',}

Methods (via Ref)

MethodReturn TypeDescription
takePhoto(type?)string | ImageDataTakes a photo. type is 'base64url' (default) or 'imgData'
takePhoto(options?)string | ImageDataTakes a photo with options. Pass { mirror: true } for mirrored capture (new in v1.1.0)
switchCamera()'user' | 'environment'Switches between front and back camera
getNumberOfCameras()numberReturns the number of available cameras
toggleTorch()booleanToggles the torch/flashlight
torchSupportedbooleanWhether the torch is supported

CropView Component (new in v1.2.0)

A separate <CropView /> component for WhatsApp-style interactive cropping. Use it after capturing a photo — it's fully independent from <Camera />.

Quick Example

import{Camera,CameraRef,CropView,CropResult}from"react-webcam-pro";constApp=()=>{constcamera=useRef<CameraRef>(null);const[photo,setPhoto]=useState<string|null>(null);const[cropped,setCropped]=useState<string|null>(null);if(cropped)return<imgsrc={cropped}alt="Cropped"/>;if(photo){return(<CropViewimage={photo}cropAspectRatio={1}// square lock (optional)onCropComplete={(result)=>setCropped(result.base64)}onCropCancel={()=>setPhoto(null)}/>);}return(<div><Cameraref={camera}/><buttononClick={()=>setPhoto(camera.current?.takePhoto()asstring)}>
📸 Capture
</button></div>);};

CropView Props

PropTypeDefaultDescription
imagestring(required)Base64 data URL of the image to crop
cropAspectRationumberundefinedLock crop to an aspect ratio (e.g. 1, 16/9). Free-form if omitted.
cropShape'rect' | 'circle''rect'Visual crop shape (output is always rectangular)
minCropSizenumber0.1Minimum crop size as fraction of image (0–1)
onCropComplete(result: CropResult) => void(required)Called with the cropped image when confirmed
onCropCancel() => voidundefinedCalled when the user cancels
labels{ confirm?, cancel?, reset? }Crop/Cancel/ResetCustom button labels
classNamestringundefinedCSS class for the container
styleCSSPropertiesundefinedInline styles for the container

CropView Methods (via Ref)

MethodReturn TypeDescription
cropImage()CropResultProgrammatically trigger crop
resetCrop()voidReset crop area to default
getCropArea()CropAreaGet current crop area (fractions 0–1)

Advanced Usage

Switching Cameras

constApp=()=>{constcamera=useRef(null);const[numberOfCameras,setNumberOfCameras]=useState(0);const[image,setImage]=useState(null);return(<><Cameraref={camera}numberOfCamerasCallback={setNumberOfCameras}/><imgsrc={image}alt="Preview"/><buttononClick={()=>setImage(camera.current.takePhoto())}>
📸 Take photo
</button><buttonhidden={numberOfCameras<=1}onClick={()=>camera.current.switchCamera()}>
🔄 Switch camera
</button></>);};

Environment Camera

<Cameraref={camera}facingMode="environment"/>

Custom Aspect Ratio

<Cameraref={camera}aspectRatio={16/9}/>

Video Constraints (new in v1.1.0)

Use videoConstraints to request a specific resolution, frame rate, or any other MediaTrackConstraints:

<Cameraref={camera}videoConstraints={{width: {ideal: 1920},height: {ideal: 1080},frameRate: {ideal: 30},}}/>

Mirrored Photo Capture (new in v1.1.0)

By default, photos are captured unmirrored (correct for environment cameras). Pass { mirror: true } to flip horizontally — useful for selfie cameras:

// With type only (existing API)constphoto=camera.current.takePhoto('base64url');// With options object (new in v1.1.0)constmirroredPhoto=camera.current.takePhoto({mirror: true});constimgData=camera.current.takePhoto({type: 'imgData',mirror: true});

Using within an iframe

<iframesrc="https://example.com/camera" allow="camera;" />

Migrating from react-camera-pro

  1. Installreact-webcam-pro:

    npm uninstall react-camera-pro
    npm install react-webcam-pro
  2. Update imports:

    - import { Camera } from "react-camera-pro";+ import { Camera } from "react-webcam-pro";
  3. That's it! The API is fully backward compatible. You can now optionally remove the errorMessages prop if you were only passing it to avoid TypeScript errors.


Development

# Install dependencies
npm install
# Run tests
npm test# Run tests in watch mode
npm run test:watch
# Build
npm run build
# Lint
npm run lint
# Type check
npm run typecheck

🤝 Community & Support

We're actively working through the open issues inherited from the original react-camera-pro repository. Fixes are being rolled out steadily.

Need something fixed urgently?Create an issue in our repo — it will be taken up on high priority and addressed quickly.


Credits


License

MIT — See LICENSE for details.

About

Universal camera component for React. Supports React 16-19, videoConstraints, mirror photos, iOS/Android, and more.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Repository files navigation

npm version

licenseTypeScriptReactDocs

react-webcam-pro

Universal Camera component for React.

Designed with focus on Android and iOS cameras. Works with standard webcams as well.

🚀 Live Demo

See browser compatibility.

Note: WebRTC is only supported on secure connections (HTTPS). You can test and debug from localhost in Chrome (this doesn't work in Safari).


🔀 Fork Notice

react-webcam-pro is a community-maintained fork of react-camera-pro by Purple Technology.

The original package has not been actively maintained for over 2 years, leaving many users with unresolved issues — including React 19 compatibility, styled-components warnings, and various bug fixes. Many of us personally needed these updates, so we decided to fork the project, fix the outstanding issues, and continue maintaining it for the community.

🙏 Acknowledgements

A huge thank you to the original creators and contributors of react-camera-pro:


✨ What's New

v1.2.0 — April 8, 2026

  • <CropView /> component — WhatsApp-style interactive crop after photo capture
  • Drag, resize, pinch — Cross-platform crop interactions (desktop + mobile)
  • Aspect ratio lock — Lock crop to 1:1, 16:9, 4:3, or free-form
  • Circle crop shape — Visual circular crop mask (output still rectangular)
  • Ref-controlledcropImage(), resetCrop(), getCropArea() via ref
  • Zero new dependencies — Uses native Canvas & Pointer Events APIs

👉 Full v1.2.0 release notes

v1.1.0 — April 7, 2026

  • videoConstraints prop — Control resolution, frame rate, and any MediaTrackConstraints (#52)
  • Mirrored photo capturetakePhoto({ mirror: true }) for selfie-correct photos (#74)
  • Fixed Firefox & iOS 15 crashgetCapabilities() handled gracefully with developer warning (#75, #77)
  • Interactive example app — Try all props live at react-webcam-pro.vercel.app

👉 Full v1.1.0 release notes

v1.0.0 — April 6, 2026 (Initial Release)

  • React 19 support — Works with React 16.8+, 17, 18, and 19
  • styled-components v6 support — Compatible with both v5 and v6
  • Fixed DOM warnings — No more mirrored and aspectRatio prop warnings (#48)
  • errorMessages is now truly optional (#63)
  • className and style props — Style the camera container easily (#47)
  • Fixed camera switching with videoSourceDeviceId — Device selection works correctly in environment mode (#62, #69)
  • Proper test suite — Jest + React Testing Library
  • Modern toolchain — TypeScript 5, Rollup 4

👉 Full v1.0.0 release notes · All releases →


Features

  • 📱 Mobile-friendly camera solution (tested on iOS and Android)
  • 📐 Fully responsive video element
    • Cover your container or define aspect ratio (16/9, 4/3, 1/1, ...)
  • 📸 Take photos as base64 JPEG or ImageData — with the same aspect ratio as the view
  • 🪞 Mirror captured photos with takePhoto({ mirror: true })
  • ✂️ WhatsApp-style crop with <CropView /> — drag, resize, aspect ratio lock (new in v1.2.0)
  • 🎛️ Custom video constraints via videoConstraints prop (resolution, fps, etc.)
  • 🖥️ Works with standard webcams and other video input devices
  • 🔄 Switch between user/environment cameras
  • 🔦 Torch/flashlight support
  • 🔢 Detect number of available cameras
  • 🔮 Facing camera is mirrored, environment is not
  • ⚡ Controlled via React Ref
  • 📝 Written in TypeScript

Installation

npm install react-webcam-pro

Peer dependencies:react, react-dom, and styled-components (v5 or v6).

📖 Documentation:amareshsm.github.io/react-webcam-pro
🎮 Try it live:react-webcam-pro.vercel.app


Quick Start

importReact,{useState,useRef}from"react";import{Camera}from"react-webcam-pro";constApp=()=>{constcamera=useRef(null);const[image,setImage]=useState(null);return(<div><Cameraref={camera}/><buttononClick={()=>setImage(camera.current.takePhoto())}>
Take photo
</button><imgsrc={image}alt="Taken photo"/></div>);};exportdefaultApp;

Props

PropTypeDefaultDescription
facingMode'user' | 'environment''user'Default camera facing mode
aspectRatio'cover' | number'cover'Aspect ratio of the video (e.g. 16/9, 4/3)
numberOfCamerasCallback(numberOfCameras: number) => void() => nullCalled when the number of cameras changes
videoSourceDeviceIdstringundefinedSpecific video device ID to use
videoConstraintsMediaTrackConstraintsundefinedCustom video constraints (resolution, fps, etc.) (new in v1.1.0)
errorMessagesobject (optional)See belowCustom error messages
videoReadyCallback() => void() => nullCalled when the video feed is ready
classNamestringundefinedCSS class name for the container
styleReact.CSSPropertiesundefinedInline styles for the container

Error Messages

All fields are optional. Defaults:

{noCameraAccessible: 'No camera device accessible. Please connect your camera or try a different browser.',permissionDenied: 'Permission denied. Please refresh and give camera permission.',switchCamera: 'It is not possible to switch camera to different one because there is only one video device accessible.',canvas: 'Canvas is not supported.',}

Methods (via Ref)

MethodReturn TypeDescription
takePhoto(type?)string | ImageDataTakes a photo. type is 'base64url' (default) or 'imgData'
takePhoto(options?)string | ImageDataTakes a photo with options. Pass { mirror: true } for mirrored capture (new in v1.1.0)
switchCamera()'user' | 'environment'Switches between front and back camera
getNumberOfCameras()numberReturns the number of available cameras
toggleTorch()booleanToggles the torch/flashlight
torchSupportedbooleanWhether the torch is supported

CropView Component (new in v1.2.0)

A separate <CropView /> component for WhatsApp-style interactive cropping. Use it after capturing a photo — it's fully independent from <Camera />.

Quick Example

import{Camera,CameraRef,CropView,CropResult}from"react-webcam-pro";constApp=()=>{constcamera=useRef<CameraRef>(null);const[photo,setPhoto]=useState<string|null>(null);const[cropped,setCropped]=useState<string|null>(null);if(cropped)return<imgsrc={cropped}alt="Cropped"/>;if(photo){return(<CropViewimage={photo}cropAspectRatio={1}// square lock (optional)onCropComplete={(result)=>setCropped(result.base64)}onCropCancel={()=>setPhoto(null)}/>);}return(<div><Cameraref={camera}/><buttononClick={()=>setPhoto(camera.current?.takePhoto()asstring)}>
📸 Capture
</button></div>);};

CropView Props

PropTypeDefaultDescription
imagestring(required)Base64 data URL of the image to crop
cropAspectRationumberundefinedLock crop to an aspect ratio (e.g. 1, 16/9). Free-form if omitted.
cropShape'rect' | 'circle''rect'Visual crop shape (output is always rectangular)
minCropSizenumber0.1Minimum crop size as fraction of image (0–1)
onCropComplete(result: CropResult) => void(required)Called with the cropped image when confirmed
onCropCancel() => voidundefinedCalled when the user cancels
labels{ confirm?, cancel?, reset? }Crop/Cancel/ResetCustom button labels
classNamestringundefinedCSS class for the container
styleCSSPropertiesundefinedInline styles for the container

CropView Methods (via Ref)

MethodReturn TypeDescription
cropImage()CropResultProgrammatically trigger crop
resetCrop()voidReset crop area to default
getCropArea()CropAreaGet current crop area (fractions 0–1)

Advanced Usage

Switching Cameras

constApp=()=>{constcamera=useRef(null);const[numberOfCameras,setNumberOfCameras]=useState(0);const[image,setImage]=useState(null);return(<><Cameraref={camera}numberOfCamerasCallback={setNumberOfCameras}/><imgsrc={image}alt="Preview"/><buttononClick={()=>setImage(camera.current.takePhoto())}>
📸 Take photo
</button><buttonhidden={numberOfCameras<=1}onClick={()=>camera.current.switchCamera()}>
🔄 Switch camera
</button></>);};

Environment Camera

<Cameraref={camera}facingMode="environment"/>

Custom Aspect Ratio

<Cameraref={camera}aspectRatio={16/9}/>

Video Constraints (new in v1.1.0)

Use videoConstraints to request a specific resolution, frame rate, or any other MediaTrackConstraints:

<Cameraref={camera}videoConstraints={{width: {ideal: 1920},height: {ideal: 1080},frameRate: {ideal: 30},}}/>

Mirrored Photo Capture (new in v1.1.0)

By default, photos are captured unmirrored (correct for environment cameras). Pass { mirror: true } to flip horizontally — useful for selfie cameras:

// With type only (existing API)constphoto=camera.current.takePhoto('base64url');// With options object (new in v1.1.0)constmirroredPhoto=camera.current.takePhoto({mirror: true});constimgData=camera.current.takePhoto({type: 'imgData',mirror: true});

Using within an iframe

<iframesrc="https://example.com/camera" allow="camera;" />

Migrating from react-camera-pro

  1. Installreact-webcam-pro:

    npm uninstall react-camera-pro
    npm install react-webcam-pro
  2. Update imports:

    - import { Camera } from "react-camera-pro";+ import { Camera } from "react-webcam-pro";
  3. That's it! The API is fully backward compatible. You can now optionally remove the errorMessages prop if you were only passing it to avoid TypeScript errors.


Development

# Install dependencies
npm install
# Run tests
npm test# Run tests in watch mode
npm run test:watch
# Build
npm run build
# Lint
npm run lint
# Type check
npm run typecheck

🤝 Community & Support

We're actively working through the open issues inherited from the original react-camera-pro repository. Fixes are being rolled out steadily.

Need something fixed urgently?Create an issue in our repo — it will be taken up on high priority and addressed quickly.


Credits


License

MIT — See LICENSE for details.

About

Universal camera component for React. Supports React 16-19, videoConstraints, mirror photos, iOS/Android, and more.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

npm version

licenseTypeScriptReactDocs

react-webcam-pro

Universal Camera component for React.

Designed with focus on Android and iOS cameras. Works with standard webcams as well.

🚀 Live Demo

See browser compatibility.

Note: WebRTC is only supported on secure connections (HTTPS). You can test and debug from localhost in Chrome (this doesn't work in Safari).


🔀 Fork Notice

react-webcam-pro is a community-maintained fork of react-camera-pro by Purple Technology.

The original package has not been actively maintained for over 2 years, leaving many users with unresolved issues — including React 19 compatibility, styled-components warnings, and various bug fixes. Many of us personally needed these updates, so we decided to fork the project, fix the outstanding issues, and continue maintaining it for the community.

🙏 Acknowledgements

A huge thank you to the original creators and contributors of react-camera-pro:


✨ What's New

v1.2.0 — April 8, 2026

  • <CropView /> component — WhatsApp-style interactive crop after photo capture
  • Drag, resize, pinch — Cross-platform crop interactions (desktop + mobile)
  • Aspect ratio lock — Lock crop to 1:1, 16:9, 4:3, or free-form
  • Circle crop shape — Visual circular crop mask (output still rectangular)
  • Ref-controlledcropImage(), resetCrop(), getCropArea() via ref
  • Zero new dependencies — Uses native Canvas & Pointer Events APIs

👉 Full v1.2.0 release notes

v1.1.0 — April 7, 2026

  • videoConstraints prop — Control resolution, frame rate, and any MediaTrackConstraints (#52)
  • Mirrored photo capturetakePhoto({ mirror: true }) for selfie-correct photos (#74)
  • Fixed Firefox & iOS 15 crashgetCapabilities() handled gracefully with developer warning (#75, #77)
  • Interactive example app — Try all props live at react-webcam-pro.vercel.app

👉 Full v1.1.0 release notes

v1.0.0 — April 6, 2026 (Initial Release)

  • React 19 support — Works with React 16.8+, 17, 18, and 19
  • styled-components v6 support — Compatible with both v5 and v6
  • Fixed DOM warnings — No more mirrored and aspectRatio prop warnings (#48)
  • errorMessages is now truly optional (#63)
  • className and style props — Style the camera container easily (#47)
  • Fixed camera switching with videoSourceDeviceId — Device selection works correctly in environment mode (#62, #69)
  • Proper test suite — Jest + React Testing Library
  • Modern toolchain — TypeScript 5, Rollup 4

👉 Full v1.0.0 release notes · All releases →


Features

  • 📱 Mobile-friendly camera solution (tested on iOS and Android)
  • 📐 Fully responsive video element
    • Cover your container or define aspect ratio (16/9, 4/3, 1/1, ...)
  • 📸 Take photos as base64 JPEG or ImageData — with the same aspect ratio as the view
  • 🪞 Mirror captured photos with takePhoto({ mirror: true })
  • ✂️ WhatsApp-style crop with <CropView /> — drag, resize, aspect ratio lock (new in v1.2.0)
  • 🎛️ Custom video constraints via videoConstraints prop (resolution, fps, etc.)
  • 🖥️ Works with standard webcams and other video input devices
  • 🔄 Switch between user/environment cameras
  • 🔦 Torch/flashlight support
  • 🔢 Detect number of available cameras
  • 🔮 Facing camera is mirrored, environment is not
  • ⚡ Controlled via React Ref
  • 📝 Written in TypeScript

Installation

npm install react-webcam-pro

Peer dependencies:react, react-dom, and styled-components (v5 or v6).

📖 Documentation:amareshsm.github.io/react-webcam-pro
🎮 Try it live:react-webcam-pro.vercel.app


Quick Start

importReact,{useState,useRef}from"react";import{Camera}from"react-webcam-pro";constApp=()=>{constcamera=useRef(null);const[image,setImage]=useState(null);return(<div><Cameraref={camera}/><buttononClick={()=>setImage(camera.current.takePhoto())}>
Take photo
</button><imgsrc={image}alt="Taken photo"/></div>);};exportdefaultApp;

Props

PropTypeDefaultDescription
facingMode'user' | 'environment''user'Default camera facing mode
aspectRatio'cover' | number'cover'Aspect ratio of the video (e.g. 16/9, 4/3)
numberOfCamerasCallback(numberOfCameras: number) => void() => nullCalled when the number of cameras changes
videoSourceDeviceIdstringundefinedSpecific video device ID to use
videoConstraintsMediaTrackConstraintsundefinedCustom video constraints (resolution, fps, etc.) (new in v1.1.0)
errorMessagesobject (optional)See belowCustom error messages
videoReadyCallback() => void() => nullCalled when the video feed is ready
classNamestringundefinedCSS class name for the container
styleReact.CSSPropertiesundefinedInline styles for the container

Error Messages

All fields are optional. Defaults:

{noCameraAccessible: 'No camera device accessible. Please connect your camera or try a different browser.',permissionDenied: 'Permission denied. Please refresh and give camera permission.',switchCamera: 'It is not possible to switch camera to different one because there is only one video device accessible.',canvas: 'Canvas is not supported.',}

Methods (via Ref)

MethodReturn TypeDescription
takePhoto(type?)string | ImageDataTakes a photo. type is 'base64url' (default) or 'imgData'
takePhoto(options?)string | ImageDataTakes a photo with options. Pass { mirror: true } for mirrored capture (new in v1.1.0)
switchCamera()'user' | 'environment'Switches between front and back camera
getNumberOfCameras()numberReturns the number of available cameras
toggleTorch()booleanToggles the torch/flashlight
torchSupportedbooleanWhether the torch is supported

CropView Component (new in v1.2.0)

A separate <CropView /> component for WhatsApp-style interactive cropping. Use it after capturing a photo — it's fully independent from <Camera />.

Quick Example

import{Camera,CameraRef,CropView,CropResult}from"react-webcam-pro";constApp=()=>{constcamera=useRef<CameraRef>(null);const[photo,setPhoto]=useState<string|null>(null);const[cropped,setCropped]=useState<string|null>(null);if(cropped)return<imgsrc={cropped}alt="Cropped"/>;if(photo){return(<CropViewimage={photo}cropAspectRatio={1}// square lock (optional)onCropComplete={(result)=>setCropped(result.base64)}onCropCancel={()=>setPhoto(null)}/>);}return(<div><Cameraref={camera}/><buttononClick={()=>setPhoto(camera.current?.takePhoto()asstring)}>
📸 Capture
</button></div>);};

CropView Props

PropTypeDefaultDescription
imagestring(required)Base64 data URL of the image to crop
cropAspectRationumberundefinedLock crop to an aspect ratio (e.g. 1, 16/9). Free-form if omitted.
cropShape'rect' | 'circle''rect'Visual crop shape (output is always rectangular)
minCropSizenumber0.1Minimum crop size as fraction of image (0–1)
onCropComplete(result: CropResult) => void(required)Called with the cropped image when confirmed
onCropCancel() => voidundefinedCalled when the user cancels
labels{ confirm?, cancel?, reset? }Crop/Cancel/ResetCustom button labels
classNamestringundefinedCSS class for the container
styleCSSPropertiesundefinedInline styles for the container

CropView Methods (via Ref)

MethodReturn TypeDescription
cropImage()CropResultProgrammatically trigger crop
resetCrop()voidReset crop area to default
getCropArea()CropAreaGet current crop area (fractions 0–1)

Advanced Usage

Switching Cameras

constApp=()=>{constcamera=useRef(null);const[numberOfCameras,setNumberOfCameras]=useState(0);const[image,setImage]=useState(null);return(<><Cameraref={camera}numberOfCamerasCallback={setNumberOfCameras}/><imgsrc={image}alt="Preview"/><buttononClick={()=>setImage(camera.current.takePhoto())}>
📸 Take photo
</button><buttonhidden={numberOfCameras<=1}onClick={()=>camera.current.switchCamera()}>
🔄 Switch camera
</button></>);};

Environment Camera

<Cameraref={camera}facingMode="environment"/>

Custom Aspect Ratio

<Cameraref={camera}aspectRatio={16/9}/>

Video Constraints (new in v1.1.0)

Use videoConstraints to request a specific resolution, frame rate, or any other MediaTrackConstraints:

<Cameraref={camera}videoConstraints={{width: {ideal: 1920},height: {ideal: 1080},frameRate: {ideal: 30},}}/>

Mirrored Photo Capture (new in v1.1.0)

By default, photos are captured unmirrored (correct for environment cameras). Pass { mirror: true } to flip horizontally — useful for selfie cameras:

// With type only (existing API)constphoto=camera.current.takePhoto('base64url');// With options object (new in v1.1.0)constmirroredPhoto=camera.current.takePhoto({mirror: true});constimgData=camera.current.takePhoto({type: 'imgData',mirror: true});

Using within an iframe

<iframesrc="https://example.com/camera" allow="camera;" />

Migrating from react-camera-pro

  1. Installreact-webcam-pro:

    npm uninstall react-camera-pro
    npm install react-webcam-pro
  2. Update imports:

    - import { Camera } from "react-camera-pro";+ import { Camera } from "react-webcam-pro";
  3. That's it! The API is fully backward compatible. You can now optionally remove the errorMessages prop if you were only passing it to avoid TypeScript errors.


Development

# Install dependencies
npm install
# Run tests
npm test# Run tests in watch mode
npm run test:watch
# Build
npm run build
# Lint
npm run lint
# Type check
npm run typecheck

🤝 Community & Support

We're actively working through the open issues inherited from the original react-camera-pro repository. Fixes are being rolled out steadily.

Need something fixed urgently?Create an issue in our repo — it will be taken up on high priority and addressed quickly.


Credits


License

MIT — See LICENSE for details.

About

Universal camera component for React. Supports React 16-19, videoConstraints, mirror photos, iOS/Android, and more.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

npm version

licenseTypeScriptReactDocs

react-webcam-pro

Universal Camera component for React.

Designed with focus on Android and iOS cameras. Works with standard webcams as well.

🚀 Live Demo

See browser compatibility.

Note: WebRTC is only supported on secure connections (HTTPS). You can test and debug from localhost in Chrome (this doesn't work in Safari).


🔀 Fork Notice

react-webcam-pro is a community-maintained fork of react-camera-pro by Purple Technology.

The original package has not been actively maintained for over 2 years, leaving many users with unresolved issues — including React 19 compatibility, styled-components warnings, and various bug fixes. Many of us personally needed these updates, so we decided to fork the project, fix the outstanding issues, and continue maintaining it for the community.

🙏 Acknowledgements

A huge thank you to the original creators and contributors of react-camera-pro:


✨ What's New

v1.2.0 — April 8, 2026

  • <CropView /> component — WhatsApp-style interactive crop after photo capture
  • Drag, resize, pinch — Cross-platform crop interactions (desktop + mobile)
  • Aspect ratio lock — Lock crop to 1:1, 16:9, 4:3, or free-form
  • Circle crop shape — Visual circular crop mask (output still rectangular)
  • Ref-controlledcropImage(), resetCrop(), getCropArea() via ref
  • Zero new dependencies — Uses native Canvas & Pointer Events APIs

👉 Full v1.2.0 release notes

v1.1.0 — April 7, 2026

  • videoConstraints prop — Control resolution, frame rate, and any MediaTrackConstraints (#52)
  • Mirrored photo capturetakePhoto({ mirror: true }) for selfie-correct photos (#74)
  • Fixed Firefox & iOS 15 crashgetCapabilities() handled gracefully with developer warning (#75, #77)
  • Interactive example app — Try all props live at react-webcam-pro.vercel.app

👉 Full v1.1.0 release notes

v1.0.0 — April 6, 2026 (Initial Release)

  • React 19 support — Works with React 16.8+, 17, 18, and 19
  • styled-components v6 support — Compatible with both v5 and v6
  • Fixed DOM warnings — No more mirrored and aspectRatio prop warnings (#48)
  • errorMessages is now truly optional (#63)
  • className and style props — Style the camera container easily (#47)
  • Fixed camera switching with videoSourceDeviceId — Device selection works correctly in environment mode (#62, #69)
  • Proper test suite — Jest + React Testing Library
  • Modern toolchain — TypeScript 5, Rollup 4

👉 Full v1.0.0 release notes · All releases →


Features

  • 📱 Mobile-friendly camera solution (tested on iOS and Android)
  • 📐 Fully responsive video element
    • Cover your container or define aspect ratio (16/9, 4/3, 1/1, ...)
  • 📸 Take photos as base64 JPEG or ImageData — with the same aspect ratio as the view
  • 🪞 Mirror captured photos with takePhoto({ mirror: true })
  • ✂️ WhatsApp-style crop with <CropView /> — drag, resize, aspect ratio lock (new in v1.2.0)
  • 🎛️ Custom video constraints via videoConstraints prop (resolution, fps, etc.)
  • 🖥️ Works with standard webcams and other video input devices
  • 🔄 Switch between user/environment cameras
  • 🔦 Torch/flashlight support
  • 🔢 Detect number of available cameras
  • 🔮 Facing camera is mirrored, environment is not
  • ⚡ Controlled via React Ref
  • 📝 Written in TypeScript

Installation

npm install react-webcam-pro

Peer dependencies:react, react-dom, and styled-components (v5 or v6).

📖 Documentation:amareshsm.github.io/react-webcam-pro
🎮 Try it live:react-webcam-pro.vercel.app


Quick Start

importReact,{useState,useRef}from"react";import{Camera}from"react-webcam-pro";constApp=()=>{constcamera=useRef(null);const[image,setImage]=useState(null);return(<div><Cameraref={camera}/><buttononClick={()=>setImage(camera.current.takePhoto())}>
Take photo
</button><imgsrc={image}alt="Taken photo"/></div>);};exportdefaultApp;

Props

PropTypeDefaultDescription
facingMode'user' | 'environment''user'Default camera facing mode
aspectRatio'cover' | number'cover'Aspect ratio of the video (e.g. 16/9, 4/3)
numberOfCamerasCallback(numberOfCameras: number) => void() => nullCalled when the number of cameras changes
videoSourceDeviceIdstringundefinedSpecific video device ID to use
videoConstraintsMediaTrackConstraintsundefinedCustom video constraints (resolution, fps, etc.) (new in v1.1.0)
errorMessagesobject (optional)See belowCustom error messages
videoReadyCallback() => void() => nullCalled when the video feed is ready
classNamestringundefinedCSS class name for the container
styleReact.CSSPropertiesundefinedInline styles for the container

Error Messages

All fields are optional. Defaults:

{noCameraAccessible: 'No camera device accessible. Please connect your camera or try a different browser.',permissionDenied: 'Permission denied. Please refresh and give camera permission.',switchCamera: 'It is not possible to switch camera to different one because there is only one video device accessible.',canvas: 'Canvas is not supported.',}

Methods (via Ref)

MethodReturn TypeDescription
takePhoto(type?)string | ImageDataTakes a photo. type is 'base64url' (default) or 'imgData'
takePhoto(options?)string | ImageDataTakes a photo with options. Pass { mirror: true } for mirrored capture (new in v1.1.0)
switchCamera()'user' | 'environment'Switches between front and back camera
getNumberOfCameras()numberReturns the number of available cameras
toggleTorch()booleanToggles the torch/flashlight
torchSupportedbooleanWhether the torch is supported

CropView Component (new in v1.2.0)

A separate <CropView /> component for WhatsApp-style interactive cropping. Use it after capturing a photo — it's fully independent from <Camera />.

Quick Example

import{Camera,CameraRef,CropView,CropResult}from"react-webcam-pro";constApp=()=>{constcamera=useRef<CameraRef>(null);const[photo,setPhoto]=useState<string|null>(null);const[cropped,setCropped]=useState<string|null>(null);if(cropped)return<imgsrc={cropped}alt="Cropped"/>;if(photo){return(<CropViewimage={photo}cropAspectRatio={1}// square lock (optional)onCropComplete={(result)=>setCropped(result.base64)}onCropCancel={()=>setPhoto(null)}/>);}return(<div><Cameraref={camera}/><buttononClick={()=>setPhoto(camera.current?.takePhoto()asstring)}>
📸 Capture
</button></div>);};

CropView Props

PropTypeDefaultDescription
imagestring(required)Base64 data URL of the image to crop
cropAspectRationumberundefinedLock crop to an aspect ratio (e.g. 1, 16/9). Free-form if omitted.
cropShape'rect' | 'circle''rect'Visual crop shape (output is always rectangular)
minCropSizenumber0.1Minimum crop size as fraction of image (0–1)
onCropComplete(result: CropResult) => void(required)Called with the cropped image when confirmed
onCropCancel() => voidundefinedCalled when the user cancels
labels{ confirm?, cancel?, reset? }Crop/Cancel/ResetCustom button labels
classNamestringundefinedCSS class for the container
styleCSSPropertiesundefinedInline styles for the container

CropView Methods (via Ref)

MethodReturn TypeDescription
cropImage()CropResultProgrammatically trigger crop
resetCrop()voidReset crop area to default
getCropArea()CropAreaGet current crop area (fractions 0–1)

Advanced Usage

Switching Cameras

constApp=()=>{constcamera=useRef(null);const[numberOfCameras,setNumberOfCameras]=useState(0);const[image,setImage]=useState(null);return(<><Cameraref={camera}numberOfCamerasCallback={setNumberOfCameras}/><imgsrc={image}alt="Preview"/><buttononClick={()=>setImage(camera.current.takePhoto())}>
📸 Take photo
</button><buttonhidden={numberOfCameras<=1}onClick={()=>camera.current.switchCamera()}>
🔄 Switch camera
</button></>);};

Environment Camera

<Cameraref={camera}facingMode="environment"/>

Custom Aspect Ratio

<Cameraref={camera}aspectRatio={16/9}/>

Video Constraints (new in v1.1.0)

Use videoConstraints to request a specific resolution, frame rate, or any other MediaTrackConstraints:

<Cameraref={camera}videoConstraints={{width: {ideal: 1920},height: {ideal: 1080},frameRate: {ideal: 30},}}/>

Mirrored Photo Capture (new in v1.1.0)

By default, photos are captured unmirrored (correct for environment cameras). Pass { mirror: true } to flip horizontally — useful for selfie cameras:

// With type only (existing API)constphoto=camera.current.takePhoto('base64url');// With options object (new in v1.1.0)constmirroredPhoto=camera.current.takePhoto({mirror: true});constimgData=camera.current.takePhoto({type: 'imgData',mirror: true});

Using within an iframe

<iframesrc="https://example.com/camera" allow="camera;" />

Migrating from react-camera-pro

  1. Installreact-webcam-pro:

    npm uninstall react-camera-pro
    npm install react-webcam-pro
  2. Update imports:

    - import { Camera } from "react-camera-pro";+ import { Camera } from "react-webcam-pro";
  3. That's it! The API is fully backward compatible. You can now optionally remove the errorMessages prop if you were only passing it to avoid TypeScript errors.


Development

# Install dependencies
npm install
# Run tests
npm test# Run tests in watch mode
npm run test:watch
# Build
npm run build
# Lint
npm run lint
# Type check
npm run typecheck

🤝 Community & Support

We're actively working through the open issues inherited from the original react-camera-pro repository. Fixes are being rolled out steadily.

Need something fixed urgently?Create an issue in our repo — it will be taken up on high priority and addressed quickly.


Credits


License

MIT — See LICENSE for details.

About

Universal camera component for React. Supports React 16-19, videoConstraints, mirror photos, iOS/Android, and more.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Repository files navigation

npm version

licenseTypeScriptReactDocs

react-webcam-pro

Universal Camera component for React.

Designed with focus on Android and iOS cameras. Works with standard webcams as well.

🚀 Live Demo

See browser compatibility.

Note: WebRTC is only supported on secure connections (HTTPS). You can test and debug from localhost in Chrome (this doesn't work in Safari).


🔀 Fork Notice

react-webcam-pro is a community-maintained fork of react-camera-pro by Purple Technology.

The original package has not been actively maintained for over 2 years, leaving many users with unresolved issues — including React 19 compatibility, styled-components warnings, and various bug fixes. Many of us personally needed these updates, so we decided to fork the project, fix the outstanding issues, and continue maintaining it for the community.

🙏 Acknowledgements

A huge thank you to the original creators and contributors of react-camera-pro:


✨ What's New

v1.2.0 — April 8, 2026

  • <CropView /> component — WhatsApp-style interactive crop after photo capture
  • Drag, resize, pinch — Cross-platform crop interactions (desktop + mobile)
  • Aspect ratio lock — Lock crop to 1:1, 16:9, 4:3, or free-form
  • Circle crop shape — Visual circular crop mask (output still rectangular)
  • Ref-controlledcropImage(), resetCrop(), getCropArea() via ref
  • Zero new dependencies — Uses native Canvas & Pointer Events APIs

👉 Full v1.2.0 release notes

v1.1.0 — April 7, 2026

  • videoConstraints prop — Control resolution, frame rate, and any MediaTrackConstraints (#52)
  • Mirrored photo capturetakePhoto({ mirror: true }) for selfie-correct photos (#74)
  • Fixed Firefox & iOS 15 crashgetCapabilities() handled gracefully with developer warning (#75, #77)
  • Interactive example app — Try all props live at react-webcam-pro.vercel.app

👉 Full v1.1.0 release notes

v1.0.0 — April 6, 2026 (Initial Release)

  • React 19 support — Works with React 16.8+, 17, 18, and 19
  • styled-components v6 support — Compatible with both v5 and v6
  • Fixed DOM warnings — No more mirrored and aspectRatio prop warnings (#48)
  • errorMessages is now truly optional (#63)
  • className and style props — Style the camera container easily (#47)
  • Fixed camera switching with videoSourceDeviceId — Device selection works correctly in environment mode (#62, #69)
  • Proper test suite — Jest + React Testing Library
  • Modern toolchain — TypeScript 5, Rollup 4

👉 Full v1.0.0 release notes · All releases →


Features

  • 📱 Mobile-friendly camera solution (tested on iOS and Android)
  • 📐 Fully responsive video element
    • Cover your container or define aspect ratio (16/9, 4/3, 1/1, ...)
  • 📸 Take photos as base64 JPEG or ImageData — with the same aspect ratio as the view
  • 🪞 Mirror captured photos with takePhoto({ mirror: true })
  • ✂️ WhatsApp-style crop with <CropView /> — drag, resize, aspect ratio lock (new in v1.2.0)
  • 🎛️ Custom video constraints via videoConstraints prop (resolution, fps, etc.)
  • 🖥️ Works with standard webcams and other video input devices
  • 🔄 Switch between user/environment cameras
  • 🔦 Torch/flashlight support
  • 🔢 Detect number of available cameras
  • 🔮 Facing camera is mirrored, environment is not
  • ⚡ Controlled via React Ref
  • 📝 Written in TypeScript

Installation

npm install react-webcam-pro

Peer dependencies:react, react-dom, and styled-components (v5 or v6).

📖 Documentation:amareshsm.github.io/react-webcam-pro
🎮 Try it live:react-webcam-pro.vercel.app


Quick Start

importReact,{useState,useRef}from"react";import{Camera}from"react-webcam-pro";constApp=()=>{constcamera=useRef(null);const[image,setImage]=useState(null);return(<div><Cameraref={camera}/><buttononClick={()=>setImage(camera.current.takePhoto())}>
Take photo
</button><imgsrc={image}alt="Taken photo"/></div>);};exportdefaultApp;

Props

PropTypeDefaultDescription
facingMode'user' | 'environment''user'Default camera facing mode
aspectRatio'cover' | number'cover'Aspect ratio of the video (e.g. 16/9, 4/3)
numberOfCamerasCallback(numberOfCameras: number) => void() => nullCalled when the number of cameras changes
videoSourceDeviceIdstringundefinedSpecific video device ID to use
videoConstraintsMediaTrackConstraintsundefinedCustom video constraints (resolution, fps, etc.) (new in v1.1.0)
errorMessagesobject (optional)See belowCustom error messages
videoReadyCallback() => void() => nullCalled when the video feed is ready
classNamestringundefinedCSS class name for the container
styleReact.CSSPropertiesundefinedInline styles for the container

Error Messages

All fields are optional. Defaults:

{noCameraAccessible: 'No camera device accessible. Please connect your camera or try a different browser.',permissionDenied: 'Permission denied. Please refresh and give camera permission.',switchCamera: 'It is not possible to switch camera to different one because there is only one video device accessible.',canvas: 'Canvas is not supported.',}

Methods (via Ref)

MethodReturn TypeDescription
takePhoto(type?)string | ImageDataTakes a photo. type is 'base64url' (default) or 'imgData'
takePhoto(options?)string | ImageDataTakes a photo with options. Pass { mirror: true } for mirrored capture (new in v1.1.0)
switchCamera()'user' | 'environment'Switches between front and back camera
getNumberOfCameras()numberReturns the number of available cameras
toggleTorch()booleanToggles the torch/flashlight
torchSupportedbooleanWhether the torch is supported

CropView Component (new in v1.2.0)

A separate <CropView /> component for WhatsApp-style interactive cropping. Use it after capturing a photo — it's fully independent from <Camera />.

Quick Example

import{Camera,CameraRef,CropView,CropResult}from"react-webcam-pro";constApp=()=>{constcamera=useRef<CameraRef>(null);const[photo,setPhoto]=useState<string|null>(null);const[cropped,setCropped]=useState<string|null>(null);if(cropped)return<imgsrc={cropped}alt="Cropped"/>;if(photo){return(<CropViewimage={photo}cropAspectRatio={1}// square lock (optional)onCropComplete={(result)=>setCropped(result.base64)}onCropCancel={()=>setPhoto(null)}/>);}return(<div><Cameraref={camera}/><buttononClick={()=>setPhoto(camera.current?.takePhoto()asstring)}>
📸 Capture
</button></div>);};

CropView Props

PropTypeDefaultDescription
imagestring(required)Base64 data URL of the image to crop
cropAspectRationumberundefinedLock crop to an aspect ratio (e.g. 1, 16/9). Free-form if omitted.
cropShape'rect' | 'circle''rect'Visual crop shape (output is always rectangular)
minCropSizenumber0.1Minimum crop size as fraction of image (0–1)
onCropComplete(result: CropResult) => void(required)Called with the cropped image when confirmed
onCropCancel() => voidundefinedCalled when the user cancels
labels{ confirm?, cancel?, reset? }Crop/Cancel/ResetCustom button labels
classNamestringundefinedCSS class for the container
styleCSSPropertiesundefinedInline styles for the container

CropView Methods (via Ref)

MethodReturn TypeDescription
cropImage()CropResultProgrammatically trigger crop
resetCrop()voidReset crop area to default
getCropArea()CropAreaGet current crop area (fractions 0–1)

Advanced Usage

Switching Cameras

constApp=()=>{constcamera=useRef(null);const[numberOfCameras,setNumberOfCameras]=useState(0);const[image,setImage]=useState(null);return(<><Cameraref={camera}numberOfCamerasCallback={setNumberOfCameras}/><imgsrc={image}alt="Preview"/><buttononClick={()=>setImage(camera.current.takePhoto())}>
📸 Take photo
</button><buttonhidden={numberOfCameras<=1}onClick={()=>camera.current.switchCamera()}>
🔄 Switch camera
</button></>);};

Environment Camera

<Cameraref={camera}facingMode="environment"/>

Custom Aspect Ratio

<Cameraref={camera}aspectRatio={16/9}/>

Video Constraints (new in v1.1.0)

Use videoConstraints to request a specific resolution, frame rate, or any other MediaTrackConstraints:

<Cameraref={camera}videoConstraints={{width: {ideal: 1920},height: {ideal: 1080},frameRate: {ideal: 30},}}/>

Mirrored Photo Capture (new in v1.1.0)

By default, photos are captured unmirrored (correct for environment cameras). Pass { mirror: true } to flip horizontally — useful for selfie cameras:

// With type only (existing API)constphoto=camera.current.takePhoto('base64url');// With options object (new in v1.1.0)constmirroredPhoto=camera.current.takePhoto({mirror: true});constimgData=camera.current.takePhoto({type: 'imgData',mirror: true});

Using within an iframe

<iframesrc="https://example.com/camera" allow="camera;" />

Migrating from react-camera-pro

  1. Installreact-webcam-pro:

    npm uninstall react-camera-pro
    npm install react-webcam-pro
  2. Update imports:

    - import { Camera } from "react-camera-pro";+ import { Camera } from "react-webcam-pro";
  3. That's it! The API is fully backward compatible. You can now optionally remove the errorMessages prop if you were only passing it to avoid TypeScript errors.


Development

# Install dependencies
npm install
# Run tests
npm test# Run tests in watch mode
npm run test:watch
# Build
npm run build
# Lint
npm run lint
# Type check
npm run typecheck

🤝 Community & Support

We're actively working through the open issues inherited from the original react-camera-pro repository. Fixes are being rolled out steadily.

Need something fixed urgently?Create an issue in our repo — it will be taken up on high priority and addressed quickly.


Credits


License

MIT — See LICENSE for details.

About

Universal camera component for React. Supports React 16-19, videoConstraints, mirror photos, iOS/Android, and more.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

npm version

licenseTypeScriptReactDocs

react-webcam-pro

Universal Camera component for React.

Designed with focus on Android and iOS cameras. Works with standard webcams as well.

🚀 Live Demo

See browser compatibility.

Note: WebRTC is only supported on secure connections (HTTPS). You can test and debug from localhost in Chrome (this doesn't work in Safari).


🔀 Fork Notice

react-webcam-pro is a community-maintained fork of react-camera-pro by Purple Technology.

The original package has not been actively maintained for over 2 years, leaving many users with unresolved issues — including React 19 compatibility, styled-components warnings, and various bug fixes. Many of us personally needed these updates, so we decided to fork the project, fix the outstanding issues, and continue maintaining it for the community.

🙏 Acknowledgements

A huge thank you to the original creators and contributors of react-camera-pro:


✨ What's New

v1.2.0 — April 8, 2026

  • <CropView /> component — WhatsApp-style interactive crop after photo capture
  • Drag, resize, pinch — Cross-platform crop interactions (desktop + mobile)
  • Aspect ratio lock — Lock crop to 1:1, 16:9, 4:3, or free-form
  • Circle crop shape — Visual circular crop mask (output still rectangular)
  • Ref-controlledcropImage(), resetCrop(), getCropArea() via ref
  • Zero new dependencies — Uses native Canvas & Pointer Events APIs

👉 Full v1.2.0 release notes

v1.1.0 — April 7, 2026

  • videoConstraints prop — Control resolution, frame rate, and any MediaTrackConstraints (#52)
  • Mirrored photo capturetakePhoto({ mirror: true }) for selfie-correct photos (#74)
  • Fixed Firefox & iOS 15 crashgetCapabilities() handled gracefully with developer warning (#75, #77)
  • Interactive example app — Try all props live at react-webcam-pro.vercel.app

👉 Full v1.1.0 release notes

v1.0.0 — April 6, 2026 (Initial Release)

  • React 19 support — Works with React 16.8+, 17, 18, and 19
  • styled-components v6 support — Compatible with both v5 and v6
  • Fixed DOM warnings — No more mirrored and aspectRatio prop warnings (#48)
  • errorMessages is now truly optional (#63)
  • className and style props — Style the camera container easily (#47)
  • Fixed camera switching with videoSourceDeviceId — Device selection works correctly in environment mode (#62, #69)
  • Proper test suite — Jest + React Testing Library
  • Modern toolchain — TypeScript 5, Rollup 4

👉 Full v1.0.0 release notes · All releases →


Features

  • 📱 Mobile-friendly camera solution (tested on iOS and Android)
  • 📐 Fully responsive video element
    • Cover your container or define aspect ratio (16/9, 4/3, 1/1, ...)
  • 📸 Take photos as base64 JPEG or ImageData — with the same aspect ratio as the view
  • 🪞 Mirror captured photos with takePhoto({ mirror: true })
  • ✂️ WhatsApp-style crop with <CropView /> — drag, resize, aspect ratio lock (new in v1.2.0)
  • 🎛️ Custom video constraints via videoConstraints prop (resolution, fps, etc.)
  • 🖥️ Works with standard webcams and other video input devices
  • 🔄 Switch between user/environment cameras
  • 🔦 Torch/flashlight support
  • 🔢 Detect number of available cameras
  • 🔮 Facing camera is mirrored, environment is not
  • ⚡ Controlled via React Ref
  • 📝 Written in TypeScript

Installation

npm install react-webcam-pro

Peer dependencies:react, react-dom, and styled-components (v5 or v6).

📖 Documentation:amareshsm.github.io/react-webcam-pro
🎮 Try it live:react-webcam-pro.vercel.app


Quick Start

importReact,{useState,useRef}from"react";import{Camera}from"react-webcam-pro";constApp=()=>{constcamera=useRef(null);const[image,setImage]=useState(null);return(<div><Cameraref={camera}/><buttononClick={()=>setImage(camera.current.takePhoto())}>
Take photo
</button><imgsrc={image}alt="Taken photo"/></div>);};exportdefaultApp;

Props

PropTypeDefaultDescription
facingMode'user' | 'environment''user'Default camera facing mode
aspectRatio'cover' | number'cover'Aspect ratio of the video (e.g. 16/9, 4/3)
numberOfCamerasCallback(numberOfCameras: number) => void() => nullCalled when the number of cameras changes
videoSourceDeviceIdstringundefinedSpecific video device ID to use
videoConstraintsMediaTrackConstraintsundefinedCustom video constraints (resolution, fps, etc.) (new in v1.1.0)
errorMessagesobject (optional)See belowCustom error messages
videoReadyCallback() => void() => nullCalled when the video feed is ready
classNamestringundefinedCSS class name for the container
styleReact.CSSPropertiesundefinedInline styles for the container

Error Messages

All fields are optional. Defaults:

{noCameraAccessible: 'No camera device accessible. Please connect your camera or try a different browser.',permissionDenied: 'Permission denied. Please refresh and give camera permission.',switchCamera: 'It is not possible to switch camera to different one because there is only one video device accessible.',canvas: 'Canvas is not supported.',}

Methods (via Ref)

MethodReturn TypeDescription
takePhoto(type?)string | ImageDataTakes a photo. type is 'base64url' (default) or 'imgData'
takePhoto(options?)string | ImageDataTakes a photo with options. Pass { mirror: true } for mirrored capture (new in v1.1.0)
switchCamera()'user' | 'environment'Switches between front and back camera
getNumberOfCameras()numberReturns the number of available cameras
toggleTorch()booleanToggles the torch/flashlight
torchSupportedbooleanWhether the torch is supported

CropView Component (new in v1.2.0)

A separate <CropView /> component for WhatsApp-style interactive cropping. Use it after capturing a photo — it's fully independent from <Camera />.

Quick Example

import{Camera,CameraRef,CropView,CropResult}from"react-webcam-pro";constApp=()=>{constcamera=useRef<CameraRef>(null);const[photo,setPhoto]=useState<string|null>(null);const[cropped,setCropped]=useState<string|null>(null);if(cropped)return<imgsrc={cropped}alt="Cropped"/>;if(photo){return(<CropViewimage={photo}cropAspectRatio={1}// square lock (optional)onCropComplete={(result)=>setCropped(result.base64)}onCropCancel={()=>setPhoto(null)}/>);}return(<div><Cameraref={camera}/><buttononClick={()=>setPhoto(camera.current?.takePhoto()asstring)}>
📸 Capture
</button></div>);};

CropView Props

PropTypeDefaultDescription
imagestring(required)Base64 data URL of the image to crop
cropAspectRationumberundefinedLock crop to an aspect ratio (e.g. 1, 16/9). Free-form if omitted.
cropShape'rect' | 'circle''rect'Visual crop shape (output is always rectangular)
minCropSizenumber0.1Minimum crop size as fraction of image (0–1)
onCropComplete(result: CropResult) => void(required)Called with the cropped image when confirmed
onCropCancel() => voidundefinedCalled when the user cancels
labels{ confirm?, cancel?, reset? }Crop/Cancel/ResetCustom button labels
classNamestringundefinedCSS class for the container
styleCSSPropertiesundefinedInline styles for the container

CropView Methods (via Ref)

MethodReturn TypeDescription
cropImage()CropResultProgrammatically trigger crop
resetCrop()voidReset crop area to default
getCropArea()CropAreaGet current crop area (fractions 0–1)

Advanced Usage

Switching Cameras

constApp=()=>{constcamera=useRef(null);const[numberOfCameras,setNumberOfCameras]=useState(0);const[image,setImage]=useState(null);return(<><Cameraref={camera}numberOfCamerasCallback={setNumberOfCameras}/><imgsrc={image}alt="Preview"/><buttononClick={()=>setImage(camera.current.takePhoto())}>
📸 Take photo
</button><buttonhidden={numberOfCameras<=1}onClick={()=>camera.current.switchCamera()}>
🔄 Switch camera
</button></>);};

Environment Camera

<Cameraref={camera}facingMode="environment"/>

Custom Aspect Ratio

<Cameraref={camera}aspectRatio={16/9}/>

Video Constraints (new in v1.1.0)

Use videoConstraints to request a specific resolution, frame rate, or any other MediaTrackConstraints:

<Cameraref={camera}videoConstraints={{width: {ideal: 1920},height: {ideal: 1080},frameRate: {ideal: 30},}}/>

Mirrored Photo Capture (new in v1.1.0)

By default, photos are captured unmirrored (correct for environment cameras). Pass { mirror: true } to flip horizontally — useful for selfie cameras:

// With type only (existing API)constphoto=camera.current.takePhoto('base64url');// With options object (new in v1.1.0)constmirroredPhoto=camera.current.takePhoto({mirror: true});constimgData=camera.current.takePhoto({type: 'imgData',mirror: true});

Using within an iframe

<iframesrc="https://example.com/camera" allow="camera;" />

Migrating from react-camera-pro

  1. Installreact-webcam-pro:

    npm uninstall react-camera-pro
    npm install react-webcam-pro
  2. Update imports:

    - import { Camera } from "react-camera-pro";+ import { Camera } from "react-webcam-pro";
  3. That's it! The API is fully backward compatible. You can now optionally remove the errorMessages prop if you were only passing it to avoid TypeScript errors.


Development

# Install dependencies
npm install
# Run tests
npm test# Run tests in watch mode
npm run test:watch
# Build
npm run build
# Lint
npm run lint
# Type check
npm run typecheck

🤝 Community & Support

We're actively working through the open issues inherited from the original react-camera-pro repository. Fixes are being rolled out steadily.

Need something fixed urgently?Create an issue in our repo — it will be taken up on high priority and addressed quickly.


Credits


License

MIT — See LICENSE for details.

About

Universal camera component for React. Supports React 16-19, videoConstraints, mirror photos, iOS/Android, and more.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Repository files navigation

npm version

licenseTypeScriptReactDocs

react-webcam-pro

Universal Camera component for React.

Designed with focus on Android and iOS cameras. Works with standard webcams as well.

🚀 Live Demo

See browser compatibility.

Note: WebRTC is only supported on secure connections (HTTPS). You can test and debug from localhost in Chrome (this doesn't work in Safari).


🔀 Fork Notice

react-webcam-pro is a community-maintained fork of react-camera-pro by Purple Technology.

The original package has not been actively maintained for over 2 years, leaving many users with unresolved issues — including React 19 compatibility, styled-components warnings, and various bug fixes. Many of us personally needed these updates, so we decided to fork the project, fix the outstanding issues, and continue maintaining it for the community.

🙏 Acknowledgements

A huge thank you to the original creators and contributors of react-camera-pro:


✨ What's New

v1.2.0 — April 8, 2026

  • <CropView /> component — WhatsApp-style interactive crop after photo capture
  • Drag, resize, pinch — Cross-platform crop interactions (desktop + mobile)
  • Aspect ratio lock — Lock crop to 1:1, 16:9, 4:3, or free-form
  • Circle crop shape — Visual circular crop mask (output still rectangular)
  • Ref-controlledcropImage(), resetCrop(), getCropArea() via ref
  • Zero new dependencies — Uses native Canvas & Pointer Events APIs

👉 Full v1.2.0 release notes

v1.1.0 — April 7, 2026

  • videoConstraints prop — Control resolution, frame rate, and any MediaTrackConstraints (#52)
  • Mirrored photo capturetakePhoto({ mirror: true }) for selfie-correct photos (#74)
  • Fixed Firefox & iOS 15 crashgetCapabilities() handled gracefully with developer warning (#75, #77)
  • Interactive example app — Try all props live at react-webcam-pro.vercel.app

👉 Full v1.1.0 release notes

v1.0.0 — April 6, 2026 (Initial Release)

  • React 19 support — Works with React 16.8+, 17, 18, and 19
  • styled-components v6 support — Compatible with both v5 and v6
  • Fixed DOM warnings — No more mirrored and aspectRatio prop warnings (#48)
  • errorMessages is now truly optional (#63)
  • className and style props — Style the camera container easily (#47)
  • Fixed camera switching with videoSourceDeviceId — Device selection works correctly in environment mode (#62, #69)
  • Proper test suite — Jest + React Testing Library
  • Modern toolchain — TypeScript 5, Rollup 4

👉 Full v1.0.0 release notes · All releases →


Features

  • 📱 Mobile-friendly camera solution (tested on iOS and Android)
  • 📐 Fully responsive video element
    • Cover your container or define aspect ratio (16/9, 4/3, 1/1, ...)
  • 📸 Take photos as base64 JPEG or ImageData — with the same aspect ratio as the view
  • 🪞 Mirror captured photos with takePhoto({ mirror: true })
  • ✂️ WhatsApp-style crop with <CropView /> — drag, resize, aspect ratio lock (new in v1.2.0)
  • 🎛️ Custom video constraints via videoConstraints prop (resolution, fps, etc.)
  • 🖥️ Works with standard webcams and other video input devices
  • 🔄 Switch between user/environment cameras
  • 🔦 Torch/flashlight support
  • 🔢 Detect number of available cameras
  • 🔮 Facing camera is mirrored, environment is not
  • ⚡ Controlled via React Ref
  • 📝 Written in TypeScript

Installation

npm install react-webcam-pro

Peer dependencies:react, react-dom, and styled-components (v5 or v6).

📖 Documentation:amareshsm.github.io/react-webcam-pro
🎮 Try it live:react-webcam-pro.vercel.app


Quick Start

importReact,{useState,useRef}from"react";import{Camera}from"react-webcam-pro";constApp=()=>{constcamera=useRef(null);const[image,setImage]=useState(null);return(<div><Cameraref={camera}/><buttononClick={()=>setImage(camera.current.takePhoto())}>
Take photo
</button><imgsrc={image}alt="Taken photo"/></div>);};exportdefaultApp;

Props

PropTypeDefaultDescription
facingMode'user' | 'environment''user'Default camera facing mode
aspectRatio'cover' | number'cover'Aspect ratio of the video (e.g. 16/9, 4/3)
numberOfCamerasCallback(numberOfCameras: number) => void() => nullCalled when the number of cameras changes
videoSourceDeviceIdstringundefinedSpecific video device ID to use
videoConstraintsMediaTrackConstraintsundefinedCustom video constraints (resolution, fps, etc.) (new in v1.1.0)
errorMessagesobject (optional)See belowCustom error messages
videoReadyCallback() => void() => nullCalled when the video feed is ready
classNamestringundefinedCSS class name for the container
styleReact.CSSPropertiesundefinedInline styles for the container

Error Messages

All fields are optional. Defaults:

{noCameraAccessible: 'No camera device accessible. Please connect your camera or try a different browser.',permissionDenied: 'Permission denied. Please refresh and give camera permission.',switchCamera: 'It is not possible to switch camera to different one because there is only one video device accessible.',canvas: 'Canvas is not supported.',}

Methods (via Ref)

MethodReturn TypeDescription
takePhoto(type?)string | ImageDataTakes a photo. type is 'base64url' (default) or 'imgData'
takePhoto(options?)string | ImageDataTakes a photo with options. Pass { mirror: true } for mirrored capture (new in v1.1.0)
switchCamera()'user' | 'environment'Switches between front and back camera
getNumberOfCameras()numberReturns the number of available cameras
toggleTorch()booleanToggles the torch/flashlight
torchSupportedbooleanWhether the torch is supported

CropView Component (new in v1.2.0)

A separate <CropView /> component for WhatsApp-style interactive cropping. Use it after capturing a photo — it's fully independent from <Camera />.

Quick Example

import{Camera,CameraRef,CropView,CropResult}from"react-webcam-pro";constApp=()=>{constcamera=useRef<CameraRef>(null);const[photo,setPhoto]=useState<string|null>(null);const[cropped,setCropped]=useState<string|null>(null);if(cropped)return<imgsrc={cropped}alt="Cropped"/>;if(photo){return(<CropViewimage={photo}cropAspectRatio={1}// square lock (optional)onCropComplete={(result)=>setCropped(result.base64)}onCropCancel={()=>setPhoto(null)}/>);}return(<div><Cameraref={camera}/><buttononClick={()=>setPhoto(camera.current?.takePhoto()asstring)}>
📸 Capture
</button></div>);};

CropView Props

PropTypeDefaultDescription
imagestring(required)Base64 data URL of the image to crop
cropAspectRationumberundefinedLock crop to an aspect ratio (e.g. 1, 16/9). Free-form if omitted.
cropShape'rect' | 'circle''rect'Visual crop shape (output is always rectangular)
minCropSizenumber0.1Minimum crop size as fraction of image (0–1)
onCropComplete(result: CropResult) => void(required)Called with the cropped image when confirmed
onCropCancel() => voidundefinedCalled when the user cancels
labels{ confirm?, cancel?, reset? }Crop/Cancel/ResetCustom button labels
classNamestringundefinedCSS class for the container
styleCSSPropertiesundefinedInline styles for the container

CropView Methods (via Ref)

MethodReturn TypeDescription
cropImage()CropResultProgrammatically trigger crop
resetCrop()voidReset crop area to default
getCropArea()CropAreaGet current crop area (fractions 0–1)

Advanced Usage

Switching Cameras

constApp=()=>{constcamera=useRef(null);const[numberOfCameras,setNumberOfCameras]=useState(0);const[image,setImage]=useState(null);return(<><Cameraref={camera}numberOfCamerasCallback={setNumberOfCameras}/><imgsrc={image}alt="Preview"/><buttononClick={()=>setImage(camera.current.takePhoto())}>
📸 Take photo
</button><buttonhidden={numberOfCameras<=1}onClick={()=>camera.current.switchCamera()}>
🔄 Switch camera
</button></>);};

Environment Camera

<Cameraref={camera}facingMode="environment"/>

Custom Aspect Ratio

<Cameraref={camera}aspectRatio={16/9}/>

Video Constraints (new in v1.1.0)

Use videoConstraints to request a specific resolution, frame rate, or any other MediaTrackConstraints:

<Cameraref={camera}videoConstraints={{width: {ideal: 1920},height: {ideal: 1080},frameRate: {ideal: 30},}}/>

Mirrored Photo Capture (new in v1.1.0)

By default, photos are captured unmirrored (correct for environment cameras). Pass { mirror: true } to flip horizontally — useful for selfie cameras:

// With type only (existing API)constphoto=camera.current.takePhoto('base64url');// With options object (new in v1.1.0)constmirroredPhoto=camera.current.takePhoto({mirror: true});constimgData=camera.current.takePhoto({type: 'imgData',mirror: true});

Using within an iframe

<iframesrc="https://example.com/camera" allow="camera;" />

Migrating from react-camera-pro

  1. Installreact-webcam-pro:

    npm uninstall react-camera-pro
    npm install react-webcam-pro
  2. Update imports:

    - import { Camera } from "react-camera-pro";+ import { Camera } from "react-webcam-pro";
  3. That's it! The API is fully backward compatible. You can now optionally remove the errorMessages prop if you were only passing it to avoid TypeScript errors.


Development

# Install dependencies
npm install
# Run tests
npm test# Run tests in watch mode
npm run test:watch
# Build
npm run build
# Lint
npm run lint
# Type check
npm run typecheck

🤝 Community & Support

We're actively working through the open issues inherited from the original react-camera-pro repository. Fixes are being rolled out steadily.

Need something fixed urgently?Create an issue in our repo — it will be taken up on high priority and addressed quickly.


Credits


License

MIT — See LICENSE for details.

About

Universal camera component for React. Supports React 16-19, videoConstraints, mirror photos, iOS/Android, and more.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Repository files navigation

npm version

licenseTypeScriptReactDocs

react-webcam-pro

Universal Camera component for React.

Designed with focus on Android and iOS cameras. Works with standard webcams as well.

🚀 Live Demo

See browser compatibility.

Note: WebRTC is only supported on secure connections (HTTPS). You can test and debug from localhost in Chrome (this doesn't work in Safari).


🔀 Fork Notice

react-webcam-pro is a community-maintained fork of react-camera-pro by Purple Technology.

The original package has not been actively maintained for over 2 years, leaving many users with unresolved issues — including React 19 compatibility, styled-components warnings, and various bug fixes. Many of us personally needed these updates, so we decided to fork the project, fix the outstanding issues, and continue maintaining it for the community.

🙏 Acknowledgements

A huge thank you to the original creators and contributors of react-camera-pro:


✨ What's New

v1.2.0 — April 8, 2026

  • <CropView /> component — WhatsApp-style interactive crop after photo capture
  • Drag, resize, pinch — Cross-platform crop interactions (desktop + mobile)
  • Aspect ratio lock — Lock crop to 1:1, 16:9, 4:3, or free-form
  • Circle crop shape — Visual circular crop mask (output still rectangular)
  • Ref-controlledcropImage(), resetCrop(), getCropArea() via ref
  • Zero new dependencies — Uses native Canvas & Pointer Events APIs

👉 Full v1.2.0 release notes

v1.1.0 — April 7, 2026

  • videoConstraints prop — Control resolution, frame rate, and any MediaTrackConstraints (#52)
  • Mirrored photo capturetakePhoto({ mirror: true }) for selfie-correct photos (#74)
  • Fixed Firefox & iOS 15 crashgetCapabilities() handled gracefully with developer warning (#75, #77)
  • Interactive example app — Try all props live at react-webcam-pro.vercel.app

👉 Full v1.1.0 release notes

v1.0.0 — April 6, 2026 (Initial Release)

  • React 19 support — Works with React 16.8+, 17, 18, and 19
  • styled-components v6 support — Compatible with both v5 and v6
  • Fixed DOM warnings — No more mirrored and aspectRatio prop warnings (#48)
  • errorMessages is now truly optional (#63)
  • className and style props — Style the camera container easily (#47)
  • Fixed camera switching with videoSourceDeviceId — Device selection works correctly in environment mode (#62, #69)
  • Proper test suite — Jest + React Testing Library
  • Modern toolchain — TypeScript 5, Rollup 4

👉 Full v1.0.0 release notes · All releases →


Features

  • 📱 Mobile-friendly camera solution (tested on iOS and Android)
  • 📐 Fully responsive video element
    • Cover your container or define aspect ratio (16/9, 4/3, 1/1, ...)
  • 📸 Take photos as base64 JPEG or ImageData — with the same aspect ratio as the view
  • 🪞 Mirror captured photos with takePhoto({ mirror: true })
  • ✂️ WhatsApp-style crop with <CropView /> — drag, resize, aspect ratio lock (new in v1.2.0)
  • 🎛️ Custom video constraints via videoConstraints prop (resolution, fps, etc.)
  • 🖥️ Works with standard webcams and other video input devices
  • 🔄 Switch between user/environment cameras
  • 🔦 Torch/flashlight support
  • 🔢 Detect number of available cameras
  • 🔮 Facing camera is mirrored, environment is not
  • ⚡ Controlled via React Ref
  • 📝 Written in TypeScript

Installation

npm install react-webcam-pro

Peer dependencies:react, react-dom, and styled-components (v5 or v6).

📖 Documentation:amareshsm.github.io/react-webcam-pro
🎮 Try it live:react-webcam-pro.vercel.app


Quick Start

importReact,{useState,useRef}from"react";import{Camera}from"react-webcam-pro";constApp=()=>{constcamera=useRef(null);const[image,setImage]=useState(null);return(<div><Cameraref={camera}/><buttononClick={()=>setImage(camera.current.takePhoto())}>
Take photo
</button><imgsrc={image}alt="Taken photo"/></div>);};exportdefaultApp;

Props

PropTypeDefaultDescription
facingMode'user' | 'environment''user'Default camera facing mode
aspectRatio'cover' | number'cover'Aspect ratio of the video (e.g. 16/9, 4/3)
numberOfCamerasCallback(numberOfCameras: number) => void() => nullCalled when the number of cameras changes
videoSourceDeviceIdstringundefinedSpecific video device ID to use
videoConstraintsMediaTrackConstraintsundefinedCustom video constraints (resolution, fps, etc.) (new in v1.1.0)
errorMessagesobject (optional)See belowCustom error messages
videoReadyCallback() => void() => nullCalled when the video feed is ready
classNamestringundefinedCSS class name for the container
styleReact.CSSPropertiesundefinedInline styles for the container

Error Messages

All fields are optional. Defaults:

{noCameraAccessible: 'No camera device accessible. Please connect your camera or try a different browser.',permissionDenied: 'Permission denied. Please refresh and give camera permission.',switchCamera: 'It is not possible to switch camera to different one because there is only one video device accessible.',canvas: 'Canvas is not supported.',}

Methods (via Ref)

MethodReturn TypeDescription
takePhoto(type?)string | ImageDataTakes a photo. type is 'base64url' (default) or 'imgData'
takePhoto(options?)string | ImageDataTakes a photo with options. Pass { mirror: true } for mirrored capture (new in v1.1.0)
switchCamera()'user' | 'environment'Switches between front and back camera
getNumberOfCameras()numberReturns the number of available cameras
toggleTorch()booleanToggles the torch/flashlight
torchSupportedbooleanWhether the torch is supported

CropView Component (new in v1.2.0)

A separate <CropView /> component for WhatsApp-style interactive cropping. Use it after capturing a photo — it's fully independent from <Camera />.

Quick Example

import{Camera,CameraRef,CropView,CropResult}from"react-webcam-pro";constApp=()=>{constcamera=useRef<CameraRef>(null);const[photo,setPhoto]=useState<string|null>(null);const[cropped,setCropped]=useState<string|null>(null);if(cropped)return<imgsrc={cropped}alt="Cropped"/>;if(photo){return(<CropViewimage={photo}cropAspectRatio={1}// square lock (optional)onCropComplete={(result)=>setCropped(result.base64)}onCropCancel={()=>setPhoto(null)}/>);}return(<div><Cameraref={camera}/><buttononClick={()=>setPhoto(camera.current?.takePhoto()asstring)}>
📸 Capture
</button></div>);};

CropView Props

PropTypeDefaultDescription
imagestring(required)Base64 data URL of the image to crop
cropAspectRationumberundefinedLock crop to an aspect ratio (e.g. 1, 16/9). Free-form if omitted.
cropShape'rect' | 'circle''rect'Visual crop shape (output is always rectangular)
minCropSizenumber0.1Minimum crop size as fraction of image (0–1)
onCropComplete(result: CropResult) => void(required)Called with the cropped image when confirmed
onCropCancel() => voidundefinedCalled when the user cancels
labels{ confirm?, cancel?, reset? }Crop/Cancel/ResetCustom button labels
classNamestringundefinedCSS class for the container
styleCSSPropertiesundefinedInline styles for the container

CropView Methods (via Ref)

MethodReturn TypeDescription
cropImage()CropResultProgrammatically trigger crop
resetCrop()voidReset crop area to default
getCropArea()CropAreaGet current crop area (fractions 0–1)

Advanced Usage

Switching Cameras

constApp=()=>{constcamera=useRef(null);const[numberOfCameras,setNumberOfCameras]=useState(0);const[image,setImage]=useState(null);return(<><Cameraref={camera}numberOfCamerasCallback={setNumberOfCameras}/><imgsrc={image}alt="Preview"/><buttononClick={()=>setImage(camera.current.takePhoto())}>
📸 Take photo
</button><buttonhidden={numberOfCameras<=1}onClick={()=>camera.current.switchCamera()}>
🔄 Switch camera
</button></>);};

Environment Camera

<Cameraref={camera}facingMode="environment"/>

Custom Aspect Ratio

<Cameraref={camera}aspectRatio={16/9}/>

Video Constraints (new in v1.1.0)

Use videoConstraints to request a specific resolution, frame rate, or any other MediaTrackConstraints:

<Cameraref={camera}videoConstraints={{width: {ideal: 1920},height: {ideal: 1080},frameRate: {ideal: 30},}}/>

Mirrored Photo Capture (new in v1.1.0)

By default, photos are captured unmirrored (correct for environment cameras). Pass { mirror: true } to flip horizontally — useful for selfie cameras:

// With type only (existing API)constphoto=camera.current.takePhoto('base64url');// With options object (new in v1.1.0)constmirroredPhoto=camera.current.takePhoto({mirror: true});constimgData=camera.current.takePhoto({type: 'imgData',mirror: true});

Using within an iframe

<iframesrc="https://example.com/camera" allow="camera;" />

Migrating from react-camera-pro

  1. Installreact-webcam-pro:

    npm uninstall react-camera-pro
    npm install react-webcam-pro
  2. Update imports:

    - import { Camera } from "react-camera-pro";+ import { Camera } from "react-webcam-pro";
  3. That's it! The API is fully backward compatible. You can now optionally remove the errorMessages prop if you were only passing it to avoid TypeScript errors.


Development

# Install dependencies
npm install
# Run tests
npm test# Run tests in watch mode
npm run test:watch
# Build
npm run build
# Lint
npm run lint
# Type check
npm run typecheck

🤝 Community & Support

We're actively working through the open issues inherited from the original react-camera-pro repository. Fixes are being rolled out steadily.

Need something fixed urgently?Create an issue in our repo — it will be taken up on high priority and addressed quickly.


Credits


License

MIT — See LICENSE for details.

About

Universal camera component for React. Supports React 16-19, videoConstraints, mirror photos, iOS/Android, and more.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages