React Cropper Component

2.3.3 · active · verified Sun Apr 19

react-cropper provides a React component wrapper for the popular Cropper.js library, enabling declarative image cropping within React applications. As of version 2.3.3, it offers robust integration with React's component lifecycle and state management, abstracting away the direct manipulation of the Cropper.js instance. It is actively maintained with frequent patch releases, focusing on bug fixes and dependency updates, ensuring compatibility and stability. Key differentiators include its direct reliance on the well-established Cropper.js, providing a familiar API for those already accustomed to the underlying library, and its comprehensive TypeScript type definitions for improved developer experience. While it wraps Cropper.js, users still need to understand the core Cropper.js options and methods, which are exposed via a ref to the component.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates how to import, render, and interact with the Cropper component using a `useRef` hook to access the underlying Cropper.js instance for image data and display a preview.

import React, { useRef, useState } from "react";
import Cropper, { ReactCropperElement } from "react-cropper";
import "cropperjs/dist/cropper.css";

const imageUrl = "https://raw.githubusercontent.com/roadmanfong/react-cropper/master/example/img/child.jpg";

const ImageCropperDemo: React.FC = () => {
  const cropperRef = useRef<ReactCropperElement>(null);
  const [croppedImage, setCroppedImage] = useState<string | null>(null);

  const onCrop = () => {
    const cropper = cropperRef.current?.cropper;
    if (cropper) {
      const dataUrl = cropper.getCroppedCanvas().toDataURL();
      console.log('Cropped data URL:', dataUrl);
      setCroppedImage(dataUrl);
    }
  };

  return (
    <div>
      <h2>React Cropper Demo</h2>
      <Cropper
        src={imageUrl}
        style={{ height: 400, width: "100%" }}
        initialAspectRatio={16 / 9}
        guides={false}
        crop={onCrop}
        ref={cropperRef}
        viewMode={1}
        minCropBoxHeight={10}
        minCropBoxWidth={10}
        background={false}
        responsive={true}
        autoCropArea={1}
        checkOrientation={false} // Important for some browsers
      />
      {croppedImage && (
        <div style={{ marginTop: '20px' }}>
          <h3>Preview</h3>
          <img src={croppedImage} alt="Cropped" style={{ maxWidth: '100%', border: '1px solid #ccc' }} />
        </div>
      )}
      <p>This demo shows how to integrate the Cropper component, set initial options, and retrieve the cropped image data using a ref.</p>
    </div>
  );
};

export default ImageCropperDemo;

view raw JSON →