React JS animating a Lottiefile on Hover

Viewed 1684

I want to take advantage of using micro-interactions on some buttons in a ReactJS app I am creating.

What I am trying to do:

When I hover/mouseEnter on an icon in a div, I want the animation to play. This is the Lottie for the icon.

EditIcon.jsx

import React, { Component } from 'react'
import Lottie from 'react-lottie'
import animationData from '../animations/edit.json'


export default class EditIcon extends Component {
constructor(props) {
    super(props);
    this.state = {
      isStopped: true,
      isPaused: true,
      Animated: 0,
    };
    this.defaultOptions = {
      loop: false,
      autoplay: false,
      animationData: animationData
    };
  }

  onMouseEnter = () => {
    this.setState({ 
        isPaused: false,
        autoplay: true,
        Animated: 0
    });
    console.log("animate");
  };

  onMouseLeave = () => {
    this.setState({ 
        isPaused: true,
        autoplay: false,
        Animated: 0
    });
    console.log("stop");
  };


  render() {
    return (
      <div id="ethdrop">
        <Lottie
          className='animation-class'
          options={this.defaultOptions}
          isStopped={this.state.isStopped}
          isPaused={this.state.isPaused}
          onMouseEnter={this.onMouseEnter} 
          onMouseLeave={this.mouseLeave}
        />
    </div>
    );
  }
}

Another oddity I found in the Stack Blitz is with the onMouseEnter function, it does not work on hover as intended. However, if I click on the icon it animated.

https://stackblitz.com/edit/react-zwlm7m

I've been searching for a solution to this but haven't found anything on S/O, most solutions are related to Jquery.

1 Answers

You can get a reference to the Lottie component and use its method play and pause.

Disclaimer i've never used react-lottie but I use lottie-react-native which seems quite similar and that's how I trigger the play/pause of the animation.

export default class EditIcon extends Component {
    _lottieHeartRef;

    ...

    onRefLottie = (ref) => {
        this._lottieHeartRef = ref;
    }

    onMouseEnter = () => {
        this._lottieHeartRef && this._lottieHeartRef.play();
        console.log("animate");
    };

    onMouseLeave = () => {
        this._lottieHeartRef && this._lottieHeartRef.pause();
        console.log("stop");
    };


    render() {
        return <div id="ethdrop">
            <Lottie
                ref={this.onRefLottie}
                ...
                onMouseEnter={this.onMouseEnter} 
                onMouseLeave={this.onMouseLeave} />
        </div>;
    }
}
Related