3

I'm assigning an onMouseEnter event to a parent element but the child is the one being triggered with this event. When I write on the console the e.target, it prints the child. How can I prevent this behavior?

I have tried the e.stopPropagation(), and updating react.

import React, { Component } from 'react';

export default class Menu extends Component {
    menuElement_Click(e) {
        // trigger change
    }

    menuItem_MouseEnter(e) {
        console.log(e.target);
    }

    render() {
        return (
            <div className='menu-container'>
                <div className='menu-item'>
                    <div className='menu-label' to='/'
                        onClick={this.menuElement_Click.bind(this)}>
                        Home
                    </div>
                </div>
                <div className='menu-item' onMouseEnter={this.menuItem_MouseEnter.bind(this)}>
                    <div className='menu-label'>About</div>
                    <div className='sub-menu'>
                        <div className='sub-menu-item' to='/about#story'
                            onClick={this.menuElement_Click.bind(this)}>
                            Story
                        </div>
                        <div className='sub-menu-item' to='/about#more'
                            onClick={this.menuElement_Click.bind(this)}>
                            More
                        </div>
                    </div>
                </div>
            </div>
        )
    }
}

On console it prints

<div className='menu-label'>About</div>

but I need it to be

<div className='menu-item'>...</div>
MRN408
  • 39
  • 1
  • 7
  • So you have mouseenter handler attached to a parent element where its child element triggering this because of event bubbling. You have two solutions for this either you check which elemet triggered this from the event.target or you can attach mouseenter handler to all the childs in the parent and stop their event bubbling. – Bikash Das Apr 06 '19 at 07:56

1 Answers1

9

Use event.currentTarget(e.currentTarget in your case). It always refers to the element to which the event handler has been attached. And about e.target: The target property of the Event interface is a reference to the object that dispatched the event.


Read more about : event.currentTarget and event.target

namth
  • 2,747
  • 1
  • 9
  • 17