user1780729
user1780729

Reputation: 518

onMouseEnter and onMouseLeave triggers on all mapped elements

I an trying to make a hover effect on my mapped items but the mouse events triggers on all items.

I am suspecting that I am loosing this or the way I change the state is wrong and I am messing it up for all elements that share it.

Here is a snipped:

  constructor(props) {
  super(props);
    this.state = {
      scale: 1,
      shadow: 0
    };
  }

  handleMouseEnter = () => {
    this.setState({
      scale: 1.1,
      shadow: 1,
    })
  }

  handleMouseLeave = () => {
    this.setState({
      scale: 1,
      shadow: 0
   })
 }

  render() {
    return (
      <div>
          {data.products.map((item, index) =>
            <Paper 
              key={index} 
              elevation={this.state.shadow} 
              style={{transform: `scale(${this.state.scale})`}}
              onMouseEnter={this.handleMouseEnter}
              onMouseLeave={this.handleMouseLeave}
            >
              {item.text}
            </Paper>
          )}
      </div>   
    );
  }

Upvotes: 0

Views: 1016

Answers (1)

Konstantin Kulikov
Konstantin Kulikov

Reputation: 31

I have the same issue.

I fix it by using onMouseOver and onMouseOut instead of onMouseEnter and onMouseLeave, and write handlers inside new container with its own state.

Something like this for your case:

First component:

constructor(props) {
    super(props);
    this.state = {

    };
}
render() {
    return (
        <div>
            {data.products.map((item, index) =>
                return <Paper key={index} />
            )}
        </div>
    );
}

Second component

constructor(props) {
    super(props);
    this.state = {
        scale: 1,
        shadow: 0
    };
}

handleMouseEnter = () => {
    this.setState({
        scale: 1.1,
        shadow: 1,
    })
}

handleMouseLeave = () => {
    this.setState({
        scale: 1,
        shadow: 0
    })
}

render() {
    return (
        <div elevation={this.state.shadow} 
             onMouseOver={this.handleMouseEnter} 
             onMouseOut={this.handleMouseLeave} 
             style={transform: `scale(${this.state.scale})`}>
                {this.props.item.text}
        </div>
    );
}

Upvotes: 1

Related Questions