Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

142
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda