I'm currently working on allowing users to upload multiple images using React and then saving them to a server.
One issue I've encountered is that sometimes when I click choose image, it works fine, but other times it does not. The same inconsistency happens with showing the images as well. Here is the code snippet I am using:
const [name, setName] = useState('');
const [description, setDescription] = useState('');
const [selectedFiles, setSelectedFiles] = useState([]);
const [isSelected, setIsSelected] = useState(false);
const fileSelectedHandler = (event) => {
console.log(event.target.files[0]);
const files = selectedFiles;
files.push(event.target.files[0]);
setSelectedFiles(files);
setIsSelected(true);
console.log(selectedFiles);
}
const fileUploadHandler = () => {
axios.post('http://')
}
return (
<div className="container">
<p>Please Enter Category name: </p>
<TextField
id="standard-multiline-flexible"
label="Name"
multiline
rowsMax={4}
variant="filled"
color="secondary"
value={name}
onChange={(event) => setName(event.target.value)}
/>
<p>Please Enter Category Description: </p>
<TextField
id="standard-multiline-flexible"
label="Description"
multiline
rowsMax={4}
variant="filled"
color="secondary"
value={description}
onChange={(event) => setDescription(event.target.value)}
/>
<input type="file" onChange={fileSelectedHandler}/>
{
selectedFiles.length > 0 ?
<div className="row">
{
selectedFiles.map((file, index) => {
console.log(file, index);
return (
<div className="column">
<img className="added_images" width="100%" src={URL.createObjectURL(file)} thumbnail />
</div>
)
})
}
</div>
:
null
}
</div>
)
and here is my CSS styling:
* {
box-sizing: border-box;
}
.container {
display: flex;
flex-direction: column;
}
.column {
float: left;
width: 33.33%;
height: 200px;
padding: 5px;
}
/* Clear floats after image containers */
.row::after {
content: "";
display: table;
clear: both;
}
During debugging, I noticed that the selectedFiles
hook does contain all the uploaded files. However, the problem lies in it not triggering the render consistently. Why could this be happening?