Registry / react-easy-crop

react-easy-crop

JSON →
library5.5.7jsnpmunverified

react-easy-crop is a React component designed for cropping images and videos with intuitive drag, zoom, and rotate interactions. It provides precise crop dimensions in both pixels and percentages, supporting various image formats (JPEG, PNG, GIF) via URL or base64 strings, as well as HTML5-supported video formats. The library is currently stable at version 5.5.7 and maintains a regular release cadence, primarily focusing on bug fixes and minor enhancements, as seen in recent patch releases. Key differentiators include its mobile-friendly design and its comprehensive feature set for media manipulation within a React application, offering a simpler alternative to more extensive image editing suites like Pintura while still providing essential cropping functionalities.

npm install react-easy-crop
INSTALL
IMPORT
SIG · REACT-EASY-CROP
R
react-easy-crop
javascriptv5.5.7
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Cropper
import Cropper from 'react-easy-crop'
import { Cropper } from 'react-easy-crop'
The main Cropper component is a default export, not a named export. Using named import will result in undefined or errors.
Cropper (CommonJS)
const Cropper = require('react-easy-crop')
For CommonJS environments, use the `require` syntax. Ensure bundler compatibility for ESM modules if migrating from older versions.
Area, Point (TypeScript types)
import type { Area, Point } from 'react-easy-crop'
These types define the shape of crop coordinates (`Point` for `x,y`) and cropped areas (`Area` for `x,y,width,height`) returned by callbacks like `onCropComplete`.

Demonstrates basic image cropping using a placeholder image, allowing drag and zoom, and then programmatically extracting the cropped portion as a new image blob. It includes a common utility function `getCroppedImage` (not part of the library) to process the raw crop coordinates into a usable image.

import { useState, useCallback } from 'react'; import Cropper from 'react-easy-crop'; // A helper function commonly used with react-easy-crop, but not exported by it const createImage = (url) => new Promise((resolve, reject) => { const image = new Image(); image.addEventListener('load', () => resolve(image)); image.addEventListener('error', (error) => reject(error)); image.setAttribute('crossOrigin', 'anonymous'); // Needed to avoid cross-origin issues for canvas operations image.src = url; }); async function getCroppedImage(imageSrc, pixelCrop) { const image = await createImage(imageSrc); const canvas = document.createElement('canvas'); const ctx = canvas.getContext('2d'); if (!ctx) { throw new Error('2D context not supported'); } const { width, height, x, y } = pixelCrop; canvas.width = width; canvas.height = height; ctx.drawImage( image, x, y, width, height, 0, 0, width, height ); return new Promise((resolve) => { canvas.toBlob((blob) => { if (!blob) { console.error('Canvas toBlob returned null'); return; } resolve(URL.createObjectURL(blob)); }, 'image/jpeg'); }); } const Demo = () => { const [imageSrc, setImageSrc] = useState('https://via.placeholder.com/600x400.png?text=Upload+Image'); const [crop, setCrop] = useState({ x: 0, y: 0 }); const [zoom, setZoom] = useState(1); const [croppedAreaPixels, setCroppedAreaPixels] = useState(null); const [croppedImage, setCroppedImage] = useState(null); const onCropComplete = useCallback((_croppedArea, _croppedAreaPixels) => { setCroppedAreaPixels(_croppedAreaPixels); }, []); const showCroppedImage = useCallback(async () => { try { if (imageSrc && croppedAreaPixels) { const croppedImageUrl = await getCroppedImage(imageSrc, croppedAreaPixels); setCroppedImage(croppedImageUrl); console.log('Cropped Image URL:', croppedImageUrl); } } catch (e) { console.error('Error cropping image:', e); } }, [imageSrc, croppedAreaPixels]); return ( <div> <div style={{ position: 'relative', width: '100%', height: 400, background: '#f0f0f0' }}> <Cropper image={imageSrc} crop={crop} zoom={zoom} aspect={4 / 3} onCropChange={setCrop} onCropComplete={onCropComplete} onZoomChange={setZoom} /> </div> <button onClick={showCroppedImage} style={{ marginTop: 20 }}> Show Cropped Image </button> {croppedImage && ( <div style={{ marginTop: 20 }}> <h3>Result</h3> <img src={croppedImage} alt="Cropped" style={{ maxWidth: '100%', height: 'auto' }} /> </div> )} </div> ); }; export default Demo;
Debug
Known issues
gotchaThe `Cropper` component is styled with `position: absolute` and requires its parent element to have `position: relative` (or other appropriate positioning) and defined dimensions (width/height). Without this, the cropper may fill the entire page or be invisible.
fix
Wrap the `<Cropper />` component in a `div` with `style={{ position: 'relative', width: '100%', height: '300px' }}` (adjust dimensions as needed).
affects: >=1.0.0
breakingVersion 5.5.4 included an important 'ESM build fix'. While intended as a fix, this may alter module resolution behavior for projects relying on older bundler configurations or specific CommonJS fallbacks. Ensure your build system correctly handles ES Modules after upgrading.
fix
Verify your bundler (Webpack, Rollup, Vite) is configured to correctly parse and resolve ES Modules. If encountering module resolution errors, consult your bundler's documentation for ESM compatibility settings, especially for packages that provide both CJS and ESM exports.
affects: >=5.5.4
gotchaThe `onCropComplete` callback provides `croppedArea` and `croppedAreaPixels` coordinates, but it does not directly return the cropped image data. To obtain the actual cropped image, you need to use these coordinates with a Canvas API to draw and export the relevant portion of the original image.
fix
Implement a separate utility function (like `getCroppedImage` shown in examples) that takes the original image source and `croppedAreaPixels` to draw the cropped section onto an HTML Canvas and export it as a Blob or Data URL.
affects: >=1.0.0
gotchaHandling image orientation (e.g., from EXIF data in mobile photos) is not directly managed by `react-easy-crop`. Images uploaded from mobile devices might appear rotated incorrectly. You will need a separate utility to read EXIF orientation and apply transformations (like canvas rotation) before passing the image to the cropper or when processing the cropped output.
fix
Before passing an image to the `Cropper`, use a library like `exif-js` or implement a custom solution to detect and correct image orientation by rotating the image on a canvas if necessary. The official examples sometimes include such helper functions for this common scenario.
affects: >=1.0.0
Errors
Common errors & fixes
Cropper is not visible or covers the entire page
The parent container of the `Cropper` component lacks `position: relative` or defined dimensions.
fix
Ensure the `<Cropper />` component is rendered inside a `div` with `position: 'relative'` and explicit `width` and `height` CSS properties (e.g., `style={{ position: 'relative', width: '100%', height: '300px' }}`).
TypeError: (0, react_easy_crop__WEBPACK_IMPORTED_MODULE_X__.default) is not a constructor
Incorrect import statement (e.g., named import for a default export) or bundler issues with ESM resolution, especially after v5.5.4.
fix
Use `import Cropper from 'react-easy-crop'` for modern ESM-compatible environments. If using CommonJS, use `const Cropper = require('react-easy-crop')`. Review your bundler configuration for ESM compatibility, particularly when upgrading to 5.5.4+.
Failed to execute 'drawImage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.
The image `src` provided to the `Cropper` component is invalid, broken, or failed to load, leading to a broken `HTMLImageElement` that cannot be drawn.
fix
Verify that the `image` prop is a valid, loaded image URL or base64 string. Check the network tab for failed image requests. Ensure any image pre-loading or error handling is in place before passing the image to `Cropper`.
Uncaught DOMException: Failed to execute 'toDataURL' on 'HTMLCanvasElement': Tainted canvases may not be exported.
Attempting to export (e.g., `toDataURL`, `toBlob`) an HTML Canvas that contains content from a cross-origin image without proper CORS headers.
fix
When loading images from external URLs, ensure the image server provides `Access-Control-Allow-Origin` headers, and set the `crossOrigin='anonymous'` attribute on the `Image` element before it loads. If these conditions are not met, the canvas becomes 'tainted' and cannot be exported for security reasons.
Upgrade
Version history
5.5.7latest on npm
Audit
Dependencies
reactrequiredPeer dependency for React component functionality.
react-domrequiredPeer dependency for rendering React components.
Agent activity
2 hits · last 30 days
node
2
Resources