Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

152
Views
React sends last element in map when passing to function

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)

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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>)
         
        })
      }
)
about 4 years ago · Juan Pablo Isaza Report

0

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.

about 4 years ago · Juan Pablo Isaza Report

0

You have to pass attribute key={myid} in your button element.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!