Codesandbox : https://codesandbox.io/s/vigilant-elgamal-dciqs
When I input an image and try to display its preview on the same container, only the image in the first container updates i.e setImage changes the value of photo for only the first component. How do I fix this?
App.js
import { useState } from "react";
import "./styles.css";
import InputContainer from './InputContainer'
export default function App() {
const [inputArr,setInputArr] = useState([])
const addInputContainer=()=>{
setInputArr([...inputArr,''])
}
return (
<div className="App">
<button onClick={addInputContainer}>Add Input-Container</button><br/>
{inputArr.map((input,index)=>{
return <InputContainer key={index}/>
})}
</div>
);
}
InputContainer.jsx
import { useState } from "react";
const InputContainer = () => {
const [image, setImage] = useState("");
const handleClick = () => {
document.querySelector(".input-image").click();
};
const handleInput = (e) => {
const selected = e.target.files[0];
if (!selected) return;
let reader = new FileReader();
reader.readAsDataURL(selected);
reader.onload = () => {
setImage(reader.result);
};
};
return (
<div className="input-container" onClick={handleClick}>
{image ? <img src={image} className="image" /> : "Click For input"}
<input
type="file"
onChange={handleInput}
className="input-image"
style={{ display: "none" }}
/>
</div>
);
};
export default InputContainer;