DEV Community

Discussion on: Hover using Reference affect both child in react components

Collapse
 
dance2die profile image
Sung M. Kim

Hi Merman.

You need to specify which ref element you want to apply hover effect on.

class ResponsivePaper extends Component {
  constructor(props) {
  }

  changeBackground(e, currRef) {
    currRef.current.style.background =
      "linear-gradient(0deg, rgba(34,193,195,1) 0%, rgba(0,0,0,1) 100%)";
    currRef.current.style.color = "white";
  }
  resetBackground(e, currRef) {
    currRef.current.style.background = "white";
    currRef.current.style.color = "black";
  }

  render() {
    const { classes } = this.props;

    return (
      <div className={classes.root} id="parent">
        <Grid container spacing={3}>
          <Grid item xs={6} sm={4} lg={3}>
            <Paper
              className={classes.paper}
              elevation={15}
              ref={this.parentRef}
              onMouseOver={e => this.changeBackground(e, this.parentRef)}
              onMouseLeave={e => this.resetBackground(e, this.parentRef)}
            >
            </Paper>
          </Grid>
        </Grid>
        <Grid container spacing={3}>
          <Grid item xs={6} sm={4} lg={3}>
            <Paper
              className={classes.paper}
              elevation={15}
              ref={this.Paper2}
              onMouseOver={e => this.changeBackground(e, this.Paper2)}
              onMouseLeave={e => this.resetBackground(e, this.Paper2)}
            >
            </Paper>
          </Grid>
        </Grid>
      </div>
    );
  }
}

Check out the forked demo - codesandbox.io/s/material-demo-9rb...