mowtheone
mowtheone

Reputation: 511

React Component State not working

I have been trying to implement a hover effect on a div-element like in this codesandbox: https://codesandbox.io/s/XopkqJ5oV

The component in which I want to do this, is a reusable component that is used multiple times on the same page. I suppose that is the reason why I can't get it to work. What am I missing?

Even using the above code won't work in my application.


EDIT: Thank you for your responses. I found the issue:

I was not letting ShouldComponentUpdate know, it should take state.isHovering into account.

 shouldComponentUpdate(nextProps, nextState) {
    return (
      nextProps.post.id !== this.props.post.id ||
      nextProps.screenshotClickUrl !== this.props.screenshotClickUrl ||
      nextProps.onImageClick !== this.props.onImageClick ||
      nextProps.handleMouseHover !== this.props.handleMouseHover ||
      nextState.isHovering !== this.state.isHovering
    )
  }

Upvotes: 0

Views: 69

Answers (1)

Dave Newton
Dave Newton

Reputation: 160191

You're missing a this in:

  toggleHoverState(state) {
    return {
      isHovering: !state.isHovering // Need a "this" to access state.
    };
  }

If you stack the elements too closely it will interfere with the mouse enter/leave events, e.g., if you space them apart:

const Foo = () => {
  return (
    <div>
      <HoverExample />
      <div style={{height: '2em', border: '1px solid blue'}} />
      <HoverExample />
    </div>
  )
}

it work like (I think) you'd expect.

https://codesandbox.io/s/93l25m453o

I put borders around it to help visualize the issue.

If that doesn't make sense, see what happens when you have the hover indicator in an adjacent span rather than stacked:

https://codesandbox.io/s/5k5jj3rpok

Upvotes: 1

Related Questions