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

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

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

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 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