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>
);
}
}
>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);
}