Home > Enterprise >  How to pick exact item after array was mapped, using useRef
How to pick exact item after array was mapped, using useRef

Time:05-20

I mapped the array to recieve a cards on my page. Then onClick I want to get each of them. This way I only get the last one "56". How can I get the one I cliked on?

import { useRef } from "react";

const arr = [22, 45, 56]

export default function AccessingElement() {
  const elementRef = useRef();

  function Click() {
     
    console.log(elementRef.current);
  }

  return (

    <div className='main'>
      {arr.map(item => (

        <div ref={elementRef}>
          <h1>here i am {item}</h1>
          <div>
            <div>
              <button onClick={(elementRef)=>Click()}>click</button>
            </div>
          </div>
        </div>
      ))}
    </div>
  )
  
}

CodePudding user response:

elementRef can only reference to one element, which in your case only references to the last element of arr. You need each card to have their own useRef. Having a separate Card component with its own useRef works.

import { useRef } from "react";

const arr = [22, 45, 56]

export default function AccessingElement() {
  return (
    <div className='main'>
      {arr.map(item => <Card key={item} item={item} />)}
    </div>
  )
}

const Card = ({ item }) => {
  const elementRef = useRef();
  function Click() {
    console.log(elementRef.current);
  }
  return (
    <div ref={elementRef}>
      <h1>here i am {item}</h1>
      <div>
        <div>
          <button onClick={Click}>click</button>
        </div>
      </div>
    </div>
  )
}
  • Related