Meet Zaveri
Meet Zaveri

Reputation: 3059

How to load image in asynchronous manner on hover effect in React.js?

You might have seen this type of effect. Example - https://codepen.io/anon/pen/GEmOQy

But I need to implement same way in React. I know I can use componentDidMount method for ajax, but thing is how to display response on hover.

I don't had practice on implementing hover with react, like I do in pure css approach with :hover.

So any solutions are welcome.

Upvotes: 0

Views: 1393

Answers (2)

Anurag Awasthi
Anurag Awasthi

Reputation: 6223

Use onMouseEnter event on the button and load a new image when it fires,

class SomeComp extends Component{
   coonstructor(){
      this.state = {
          url: 'http://some-intial-url.com'
      }
      this.onMouseEnter = this.onMouseEnter.bind(this)
   }
   onMouseEnter(){
       this.setState({
          url: GetOtherImageURl()
       })
   }
   render(){
      <img src = {this.state.url} />
   }
}

Upvotes: 0

Dane
Dane

Reputation: 9532

This a very flat question, and there are many possibilities. All I can give is a basic skeleton on how to do it.
Define a ImageCard component in whose componentDidMount you do the API call. Then on your parent component ( whichevere component the button is ), store a state key that manages whether to show the card or not:

class MyComponent extends React.Component {
  constructor() {
    super();
    this.state = {
      showCard: false
    };
  }
  render () {
    return (
      <div>
        {
          this.state.showCard &&
        <ImageCard/>
        }
        <button
          onMouseEnter={() => this.setState({ showCard: true })}
          onMouseLeave={() => this.setState({ showCard: false })}
          >Hover Me!</button>
      </div>
    )
  }
}

Upvotes: 1

Related Questions