2

I have a React component that has an implemented hover effect, as such:

let style = {
  backgroundColor: "blue"
}

class someComponent extends React.Component{

  constructor(props){
    super(props)

    this.state = {
      hover: false
    }
  }

  handleHover(event) {
    this.setState({ hover: true });
  }

  handleExit(event) {
    this.setState({ hover: false });
  }

  render(){
    if(this.state.hover){
      style.backgroundColor = "red"
    } else {
      style.backgroundColor = "blue"
    }

    return(
      <Segment style={style} onMouseEnter={this.handleHover} onMouseLeave={this.handleExit} />
    );
  }
}

However, even though it does work, I get an error saying:

Warning: div was passed a style object that has previously been mutated. Mutating style is deprecated. Consider cloning it beforehand. Check the render of Segment.

I looked up the answer from this post, and it says to implement it this way:

const {styleFromProps} = this.props;

const newStyle = {...styleFromProps, marginTop: '45px'};

However, my style is defined outside of the class, and I'm not passing any styling down from the parent component. So I'm not too sure how to implement this answer into my current code.

Question(s):

  • Is that answer the best way to implement a hover effect, or should I clone the component like the error suggests?
  • How should I implement the answer into my current component? The structure can be changed if necessary.
Andrew Li
  • 47,104
  • 10
  • 106
  • 132
Phillip
  • 2,486
  • 3
  • 21
  • 39
  • In case there's any confusion I excluded the .bind(this) statements for the handle functions from the constructor for the sake of this post – Phillip Aug 29 '17 at 02:29

1 Answers1

1

Just use the hover state to determine the style instead of storing it in a separate object. Because the background color depends on state, don't store it outside the component, tie it to state with a ternary operator:

<Segment style={{
  backgroundColor: this.state.hover ? 'red' : 'blue'
}} />

And if you have other styles, just use spread syntax:

<Segment style={{
  ...styleObj,
  backgroundColor: this.state.hover ? 'red' : 'blur'
}} />

This will copy all the styles you already have in styleObj then also apply background color. You can learn more about spread syntax in React JSX here.

Andrew Li
  • 47,104
  • 10
  • 106
  • 132
  • For this post I didn't include all the styling required in this object. So If it's necessary that I use a style object, how would I implement it? My style object has more styling than just a background color change – Phillip Aug 29 '17 at 02:33
  • @PhillipR Edited. – Andrew Li Aug 29 '17 at 02:35