sosick
sosick

Reputation: 622

How to make hover event on single component?

I want to display h4 photo title on photo, but only if photo hovered. I was trying do this using onMouseEnter and onMouseLeave, but if I using many the same components, and when I hovered one of them, every components on page displaying photo title. Can I do something in my code to display title only on hovered photo?

Single Photo:

const Photo = props => (
  <div onMouseEnter={props.onMouseEvent} 
       onMouseLeave={props.onMouseEvent} 
       style={props.backgroundImage}>
    <h4>{props.hovered && props.title}</h4>
  </div>
); 

Displaying many Photo components:

class Gallery extends Component {
  state = {
    photos: [], // fetched photos here
    hovered: false
  };

  toggleMouseHover = () => this.setState(prev => ({ hovered: !prev.hovered }));

  render() {

    return (
        {this.state.photos.map(photo => {
          <Photo
            backgroundImage={{ backgroundImage: `url(${photo.src})` }}
            title={photo.title}
            onMouseEvent={this.toggleMouseHover}
            hovered={this.state.hovered}
          />
        })}
    );
  }
}

I was thinking about using content in CSS ::before or ::after, but I can not do it in React.

Upvotes: 0

Views: 65

Answers (1)

spaniard
spaniard

Reputation: 560

You can do this with pure css, it shouldn't matter that you are using react.

Single Photo:

const Photo = props => (
  <div style={props.backgroundImage} className="div-photo">
    <h4 className="photo-title">{props.title}</h4>
  </div>
); 

Css:

div.div-photo:hover > h4.photo-title {
     display: block;
}

div.div-photo > h4.photo-title {
    display: none;
}

I think this should work. You can use attribute visibility if you prefer it. Also, as mentioned in the comments, attribute opacity is a good option if you want to use fade-in/fade-out effects.

Upvotes: 3

Related Questions