Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

140
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda