Last active
July 8, 2020 20:55
-
-
Save yoavniran/769fa16d379289b529617e1b2d16bd14 to your computer and use it in GitHub Desktop.
ItemPreviewWithCrop.jsx - react-uploady demo
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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