I have a simple list where in each element there is an input to choose an image to upload. The choosen image is displaying correctly, but I can't manage to choose different images for different elements.
My list seems to render the same value for all items. My issue is that any image will be present in all elements. I want a different image for each element.
This is what I tried so far :
const handleChange = (index, newimage) => {
const cloneList = [...list];
cloneList[index].image = newimage;
setList(cloneList);
};
https://codesandbox.io/s/cool-sid-74le8?file=/src/App.js
import React, { useState } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
export default () => {
const initialList = [
{
id: "1",
image: "https://picsum.photos/150/150.jpg"
},
{
id: "2",
image: " "
},
{
id: "3",
image: " "
}
];
const [list, setList] = React.useState(initialList);
const [file, setFile] = useState(null);
const handleFile = (event) => {
setFile(URL.createObjectURL(event.target.files[0]));
};
/* What I tried to change a specific element
const handleChange = (index, newimage) => {
const cloneList = [...list];
cloneList[index].image = newimage;
setList(cloneList);
};*/
return (
<div>
<ul>
<div>
{list.map((item, index) => (
<li key={item.id}>
<span>
<input type="file" onChange={handleFile} />
<img
src={file}
alt=""
style={{ width: "100px", height: "100px" }}
/>
</span>
</li>
))}
</div>
</ul>
</div>
);
};
setListtofile? Sorry i'm still new to react.imageproperty on the cloned list because nested objects are not cloned. See this answer: https://stackoverflow.com/questions/37662708/react-updating-state-when-state-is-an-array-of-objects