I am creating image upload component to allow for multiple image upload. I want to enable user to consecutively add images until the limit is reached. Files references are stored in state and state is consecutively updated. Upon the first file selection state is accordingly updated but the trouble comes on second consecutive selection where it throws an error.
import React, { useRef, useState, useEffect } from "react";
import Button from "./Button";
import "./ImageUpload.css";
const ImageUpload = (props) => {
const [file, setFile] = useState([]);
const imagePickerRef = useRef();
useEffect(() => {
if (!file.length) {
return;
}
console.log(file);
}, [file]);
const imagePickerHandler = () => {
imagePickerRef.current.click();
};
const imagePickedHandler = (event) => {
if (
event.target.files &&
event.target.files.length + file.length <= 10
) {
setFile(prevFiles => [...prevFiles, ...event.target.files]);
}
};
return (
<div className="form-control">
<input
id={props.id}
type="file"
accept=".jpg, .jpeg, .png"
style={{ display: "none" }}
ref={imagePickerRef}
onChange={imagePickedHandler}
multiple
/>
<Button type="button" onClick={imagePickerHandler}>
PICK IMAGE
</Button>
</div>
);
};
export default ImageUpload;