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

156
Views
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 answers
Answer question

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 Report

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