eatorres
eatorres

Reputation: 179

React - onmouseenter doesn't work between child elements

I am trying to implement a menu that shows up on hover. The problem is that the menu hides while hovering between the DropdownOption child elements, so whenever I hover between options 1 and 2. Each child is a div and has a margin of 0px

  openDropdown = () => {
    this.setState({showList: true})
  }

  closeDropdown = () => {
    this.setState({showList: false})
  }

  showList = () => {
    return (
      <DropdownContainer onMouseEnter={this.openDropdown} onMouseLeave={this.closeDropdown}>
          <DropdownOption>Option1</DropdownOption>
          <DropdownOption>Option2</DropdownOption>
      </DropdownContainer>
    )
  }

render () {
    return (
      <div onMouseEnter={this.openDropdown}>
        <MenuButtonContainer>
          Title
        </MenuButtonContainer>
        {this.state.showList ? this.showList() : null}
      </div>
    )
  }

Upvotes: 0

Views: 821

Answers (1)

Samuel
Samuel

Reputation: 2442

This sounds like an event bubbling issue.

Where you have your event listener callbacks, e.g.:

openDropdown = () => {
  this.setState({showList: true})
}

Try accessing the event object by including it as a parameter to the function. Then on the event object, call stopPropagation() E.g:

openDropdown = (event) => {
  event.stopPropagation()
  this.setState({showList: true})
}

Upvotes: 1

Related Questions