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

152
Vistas
How can I get key (prop) from a ref on another element?

I am trying to get the the key from a element that is mapped from a database ( I am only saying this so nobody suggests to useState)

listedItems.map((e)=> ( 
<div
ref={ref}
key={e.openRequestDocId}> // Need to get this Key
<button onClick={()=> console.log(ref)}
>get Key from useRef</button>
</div>

I have created a codeSandbox mockup of where I am at. Basically, I have a ref from React.useRef(), and I am trying to get the key prop from the parent div.

https://codesandbox.io/s/mutable-sea-5qony2?file=/src/App.js

All help is appreciated!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

you can attach additional data to ref(s) using useImperativeHandle hook like the following:

import React, { useRef, useImperativeHandle } from "react";

export default function App() {
  const ref = useRef();

  useImperativeHandle(ref, () => ({
    key: "A3hNc95uj"
  }));
  const handleClick = () => {
    console.log(ref);
  };
  return (
    <div className="App" key={"A3hNc95uj"} ref={ref}>
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button onClick={handleClick}>Log Key from parent div</button>
    </div>
  );
}

about 4 years ago · Juan Pablo Isaza Denunciar

0

Set your key in a data- attribute (for a simple name right now: data-key). And then from the ref, since you get the div element, you can fetch it again by doing ref.current.dataset.key

The only downside of this approach is that the key will be visible in the DOM. If that shouldn't be the case then you can create a closure for the button onClick with the key

<button onClick={(event) => myfunction(event, e.openRequestDocId)}>
get Key from useRef
</button>

This way, your click handler will get the required key onClick

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