Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display the title of the element on which I hovered in the console

I have a list that has a "text" field. I display the list on the page. And each element has an onMouseEnter event.

I need to display the text of the element I hovered over when hovering over an element. Now the entire list is displayed in the console. How can i do this?

export default class List extends Component {
  constructor(props) {
    super(props);

    this.state = {
      list: [
        {
          id: 1,
          text: "Text1",
        },
        {
          id: 2,
          text: "Text2",
        },
        {
          id: 3,
          text: "Text3",
        },
      ],
    };

    this.hoverHandler = this.hoverHandler.bind(this);
  }

  hoverHandler() {
    console.log(this.state.list);
  }
  render() {
    return (
      <div>
        <ul>
          {this.state.list.map((item) => (
            <li
              key={item.id}
              onMouseEnter={this.hoverHandler}
            >
              {item.text}
            </li>
          ))}
        </ul>
      </div>
    );
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First you’d need to identify which element is hovered. For example, you can pass an identifier to the handler function:

onMouseEnter={() => this.hoverHandler(item.id)}

Then in that function use that identifier to find the one record you want:

hoverHandler(id) {
  console.log(this.state.list.find(x => x.id === id));
}

If you just want to display one property on that array item, then just display that one property:

hoverHandler(id) {
  console.log(this.state.list.find(x => x.id === id)?.text);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading