Restore a crop
Save croppedArea to localStorage and restore it on the next load.
Loading example...
Code
import { useState } from 'react'
import Cropper, { type Area, type Point } from 'react-easy-crop'
const STORAGE_KEY = 'react-easy-crop-demo-crop'
type RestoreExampleProps = {
image: string
}
export default function RestoreExample({ image }: RestoreExampleProps) {
const [crop, setCrop] = useState<Point>({ x: 0, y: 0 })
const [zoom, setZoom] = useState(1)
const [initialCroppedAreaPercentages, setInitialCroppedAreaPercentages] = useState<
Area | undefined
>(readSavedCrop)
const [croppedArea, setCroppedArea] = useState<Area | null>(null)
function onCropComplete(area: Area) {
setCroppedArea(area)
}
function saveCrop() {
if (!croppedArea) {
return
}
localStorage.setItem(STORAGE_KEY, JSON.stringify(croppedArea))
setInitialCroppedAreaPercentages(croppedArea)
}
function resetCrop() {
localStorage.removeItem(STORAGE_KEY)
setCrop({ x: 0, y: 0 })
setZoom(1)
setInitialCroppedAreaPercentages(undefined)
}
return (
<>
<div className="cropper">
<Cropper
key={JSON.stringify(initialCroppedAreaPercentages)}
image={image}
crop={crop}
zoom={zoom}
aspect={4 / 3}
initialCroppedAreaPercentages={initialCroppedAreaPercentages}
onCropChange={setCrop}
onCropComplete={onCropComplete}
onZoomChange={setZoom}
/>
</div>
<button onClick={saveCrop}>Save crop</button>
<button onClick={resetCrop}>Reset</button>
</>
)
}
function readSavedCrop() {
const savedCrop = localStorage.getItem(STORAGE_KEY)
if (!savedCrop) {
return undefined
}
try {
return JSON.parse(savedCrop) as Area
} catch {
return undefined
}
}