DEV Community

Herman Ng
Herman Ng

Posted on

Hover using Reference affect both child in react components

Hi guys, What I'm trying to do here

When I hover the Child Component,
The background change (That's a good start).

But both of the Child Component background colours change. Should be just box that I hover over.

Any help would be very much appreciated.
Thank you
This is an URL to refer to my code
https://codesandbox.io/s/material-demo-sck7e?fontsize=14&hidenavigation=1&theme=dark

Top comments (1)

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...