I am trying to use react-easy-crop to crop an image and then upload it to an Django rest api through a form. I am new to react and the tutorials I have seen only show for one image while I want to make it work for 3 input fields in the form. I have a separate react child component with all the cropper tools:
export function CropEasy(myImage, setOpenCrop) {
let [crop, setCrop] = useState({ x: 0, y: 0 })
let [zoom, setZoom] = useState(1)
let [rotation, setRotation] = useState(0)
let [croppedAreaPixels, setCroppedAreaPixels] = useState(null)
let cropComplete = (croppedArea, croppedAreaPixels) => {
setCroppedAreaPixels(croppedAreaPixels)
}
let cropImage = async () => {
}
return (
<div>
<DialogContent dividers
sx={{
backgroud: "#333",
position: 'relative',
height: 400,
width: "auto",
minWidth: { sm: 500 }
}}
>
<Cropper
image={myImage}
crop={crop}
zoom={zoom}
rotation={rotation}
aspect={16 / 9}
onZoomChange={setZoom}
onRotationChange={setRotation}
onCropChange={setCrop}
onCropComplete={cropComplete}
/>
</DialogContent>
<DialogActions sx={{ flexDirection: "column", mx: 3, my: 2 }}>
<Box sx={{
display: 'flex',
gap: 2,
flexWrap: "wrap"
}}>
<Button
variant="outlined"
startIcon={<Cancel />}
onClick={() => setOpenCrop('d-none')}
>
Cancel
</Button>
<Button
variant="contained"
startIcon={<CropIcon />}
onClick={cropImage}
>
Crop
</Button>
</Box>
</DialogActions>
</div>
)
}
The problem I have is that I am not sure how to connect this to my inputs so that the image is selected and the crop pops up then I crop the image and then it is kept in the form's input field ready to be submitted with the cropped images. The input looks something like this <input type='file' accept="image/*" onChange={(e) => imageHandler(e)} name="image-1" />
With the function:
let imageHandler = (e) => {
if (e.target.files && e.target.files.length >0) {//chekck if the file is empty
let file = e.target.files[0]
let reader = new FileReader()
reader.readAsDataURL(file)
reader.addEventListener("load", ()=>{
//setFile(reader.result)
setPhotoURL(reader.result)
})
console.log("image loaded")
setOpenCrop('d-block')
}
}
The form is the parent component while the cropper component is the child component which I am aware is not the best approach. I just do not know how to connect it at the moment correctly. So far I tried adding the image to the state of the parent component where the form is and then change the display of the cropper component to block but although the component shows the image does not and it triggers a get request to my Django server for some reason. I would like some guidance as I know my approach probably won't work. Thank you so much.