DEV Community

Herman Ng
Herman Ng

Posted on

1

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

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay