I am trying to create dynamic UI elements using react and have created a loop of elements by mapping over an array and on clicking the element, it passes the values to a function. My code looks something like below
const [shortlistedIds, setShortlistedIds] = useState([]);
const attachmentInputRef = useRef();
const handleOpenFilePicker = async () => {
attachmentInputRef.current.click();
};
//somewhere in code, set the IDs
setShortlistedIds(["1", "2", "3", "4"]);
const handleFilePicker = async(e) => {
console.log(e.target.id)
let uploadFiles = [...e.target.files]
const apiRes = await api.createAttachment(e.target.id, uploadFiles)
}
return(
{shortlistedIds.map((myId) => (
<button
id={myId}
className="attachment-button pull-right"
onClick={handleOpenFilePicker}
style={{ position: "absolute" }}
>
click me {myId}
</button>
<input
id={myId}
ref={attachmentInputRef}
type="file"
style={{ display: "none" }}
name="file"
onChange={(e) => {handleFilePickerChange(myId, e);}}
multiple
/>
)
)};
)
The html is rendered properly with correct id and text for each button but on clicking, the value printed in console from the handleFilePicker is always the last ID, "4" from above example, not matter which button I click. Not sure what the issue is here. (please ignore any typos as this is an example code based on the actual code. It is not feasible to paste the actual code here)
Make it simple
const [shortlistedIds, setShortlistedIds] = useState([]);
useEffect(() => {
setShortlistedIds(["1", "2", "3", "4"]);
}, [])
const targetClick = (e)=>{
console.log(e);
}
return (
{
shortlistedIds.map(myId => {
return(<button onClick={() =>targetClick(myId)} key={myId}>click me{myId}</button>)
})
}
)
The problem in the above case is that the useRef() points to a reference and thus, reassigning it changes the value each time it is assigned in the map, finally assigning to the final value. The useRef() hook is not replicated with each assignment in the input field.
To solve this, I moved the input block to a child component which created a useRef() hook for each of the input fields and thus works fine.
You have to pass attribute key={myid} in your button element.