Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ItemPreviewWithCrop.jsx - react-uploady demo
import ReactCrop from "react-image-crop";
import { withRequestPreSendUpdate, useItemFinalizeListener } from "@rpldy/uploady";
import { PREVIEW_TYPES } from "@rpldy/upload-preview";
import cropImage from "./image-crop-helper";
const ItemPreviewWithCrop = withRequestPreSendUpdate(props => {
const { id, url, isFallback, type, updateRequest, requestData, previewMethods } = props;
const [finished, setFinished] = useState(false);
const [crop, setCrop] = useState(null);
useItemFinalizeListener(() => {
setFinished(true);
}, id);
const onUploadCrop = useCallback(async () => {
if (updateRequest && (crop?.height || crop?.width)) {
requestData.items[0].file = await cropImage(
url,
requestData.items[0].file,
crop
);
updateRequest({ items: requestData.items });
}
}, [url, requestData, updateRequest, crop]);
const onUploadCancel = useCallback(() => {
updateRequest(false);
if (previewMethods.current?.clear) {
previewMethods.current.clear();
}
}, [updateRequest, previewMethods]);
return isFallback || type !== PREVIEW_TYPES.IMAGE ? (
<img src={url} alt="fallback img" />
) : (
<>
{requestData && !finished ? (
<ReactCrop
src={url}
crop={crop}
onChange={setCrop}
onComplete={setCrop}
/>
) : (
<img src={url} alt="uploading img" />
)}
<PreviewButtons
finished={finished}
crop={crop}
updateRequest={updateRequest}
onUploadCancel={onUploadCancel}
onUploadCrop={onUploadCrop}
/>
<p>{finished ? "FINISHED" : ""}</p>
</>
);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment