Skip to content

Instantly share code, notes, and snippets.

@roelbarreto
Created April 16, 2019 00:51
Show Gist options
  • Save roelbarreto/752c3152dd0a6bda61e849ca48d6dff5 to your computer and use it in GitHub Desktop.
Save roelbarreto/752c3152dd0a6bda61e849ca48d6dff5 to your computer and use it in GitHub Desktop.
Sample CroppperJS Wrapper
import React, {
useEffect,
useLayoutEffect,
useState,
useCallback,
RefObject
} from "react";
import CropperJS from "cropperjs";
import "cropperjs/dist/cropper.css";
import { Spinner } from "office-ui-fabric-react";
export type CropperCropEvent = CustomEvent<CropperJS.Data>;
export type CropData = CropperJS.Data;
type CropEvent = (event: CropperCropEvent) => void;
type CropperProps = {
imageRef: RefObject<HTMLImageElement>;
src: string;
viewMode: CropperJS.ViewMode;
height: number;
width: string | number | undefined;
aspectRatio: number;
crop?: CropEvent;
};
const Cropper: React.FC<CropperProps> = props => {
const { src, aspectRatio, crop, height, width, viewMode } = props;
const loading = useCropper(src, props.imageRef, {
aspectRatio,
viewMode,
crop
});
return (
<div className="overlay-spinner" style={{ height }}>
<img key={src} ref={props.imageRef} src={src} style={{ width, height }} />
{loading && <Spinner />}
</div>
);
};
/**
* @description Same as ComponentDidMount/ComponentWillUnmount
* @param imgRef Html Image Element to cropped
* @param options {CropperJS.Options}
*/
function useCropper(
src: string,
imgRef: React.RefObject<HTMLImageElement>,
options: CropperJS.Options
): boolean {
const [loading, setLoading] = useState(true);
const cropCb: CropEvent = function(ev) {
if (options.crop) {
options.crop(ev);
}
};
const handleCrop = useCallback(cropCb, [options.crop]);
useLayoutEffect(() => {
if (imgRef.current) {
const cropper = new CropperJS(imgRef.current, {
checkCrossOrigin: true,
checkOrientation: false,
aspectRatio: options.aspectRatio,
viewMode: options.viewMode,
crop: handleCrop,
autoCrop: true,
autoCropArea: 1,
ready: () => setLoading(false)
});
return () => {
cropper.destroy();
};
}
}, [imgRef.current, options.viewMode, options.aspectRatio, src]);
return loading;
}
export default Cropper;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment