Skip to content

Commit

Permalink
fix: update zoomTo handling
Browse files Browse the repository at this point in the history
  • Loading branch information
shekhar-shubhendu committed Apr 26, 2021
1 parent 4b71ab9 commit 50c1fa4
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 22 deletions.
39 changes: 19 additions & 20 deletions src/react-cropper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,25 @@ const ReactCropper = React.forwardRef<ReactCropperElement | HTMLImageElement, Re
const defaultOptions: ReactCropperDefaultOptions = {scaleY, scaleX, enable, zoomTo, rotateTo};
const innerRef = useRef<HTMLImageElement>(null);
const combinedRef = useCombinedRefs(ref, innerRef);

/**
* Invoke zoomTo method when cropper is set and zoomTo prop changes
*/
useEffect(() => {
if (combinedRef.current?.cropper && typeof zoomTo === 'number') {
combinedRef.current.cropper.zoomTo(zoomTo);
}
}, [props.zoomTo]);

/**
* re-render when src changes
*/
useEffect(() => {
if (combinedRef.current?.cropper && typeof src !== 'undefined') {
combinedRef.current.cropper.reset().clear().replace(src);
}
}, [src]);

useEffect(() => {
if (combinedRef.current !== null) {
const cropper = new Cropper(combinedRef.current, {
Expand All @@ -100,26 +119,6 @@ const ReactCropper = React.forwardRef<ReactCropperElement | HTMLImageElement, Re
};
}, [combinedRef]);

/**
* do zooming when param zoomTo is changed (passing data to cropperjs)
*/
useEffect(() => {
const currentRef: any = combinedRef.current;
if(currentRef && currentRef?.cropper?.canvasData && typeof props?.zoomTo === 'number') {
const cropper = currentRef.cropper;
cropper.zoomTo(props.zoomTo);
}
},[props.zoomTo]);

/**
* re-render when src changes
*/
useEffect(() => {
if (combinedRef.current?.cropper && typeof src !== 'undefined') {
combinedRef.current.cropper.reset().clear().replace(src);
}
}, [src]);

return (
<div style={style} className={className}>
<img
Expand Down
4 changes: 2 additions & 2 deletions tests/react-cropper.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,9 +56,9 @@ describe('Cropper Render Tests', () => {
expect(ref.src).toEqual(newImage);
});

test('renders cropper with zoomTo prop', async () => {
test('renders cropper with zoomTo prop', async () => {
const onInitialized = jest.fn();
render(<Cropper src={image} onInitialized={onInitialized} zoomTo={1} />);
render(<Cropper src={newImage} onInitialized={onInitialized} zoomTo={1} />);
await waitFor(() => expect(onInitialized).toHaveBeenCalledTimes(1));
});
});
Expand Down

0 comments on commit 50c1fa4

Please sign in to comment.