skip to Main Content

My Code : https://codesandbox.io/s/quirky-wescoff-44n2by?file=/src/App.js

When I hover over any element, always the last element of array is printed in console.

I tried using ref, not sure if I am doing it right.


I expected on hover over any element that elements content will be console logged.

Please suggest any way on how to access any elements content on hover.

( I’ll delete this question once its been answered, there were similar questions asked before but I was not able to get them, Gracias! in advance )

2

Answers


  1. Pass the index of the current element as an argument to the enterMouse function.

    import "./styles.css";
    import { useRef } from "react";
    
    export default function App() {
      const array = [12, 34, 54, 122, 0];
      const myRef = useRef(null);
    
      function enterMouse(index) {
        console.log(array[index]);
      }
    
      return (
        <div className="App">
          {array.map((e, index) => (
            <h1
              onMouseEnter={() => {
                enterMouse(index);
              }}
              ref={myRef}
            >
              {e}
            </h1>
          ))}
        </div>
      );
    }
    
    Login or Signup to reply.
  2. If I understand your question correctly, you can achieve it without using useRef as follows:

    
      const array = [12,34,54,122,0];
    
      function enterMouse(event){
        console.log(event.target.innerHTML)
      }
    
      return (
        <div className="App">
          {
            array.map((e,index)=>
            <h1 key={index} onMouseEnter={enterMouse}>{e}</h1>)
          }
        </div>
      );
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search