Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to click an image and make a rotation

I have below reactjs code. It renders an image dom. I want to implement a feather that when a user click on that image, the image is rotated 180 degrees. And at the end of the rotate animation, replace it with a new image. How can I implement it in reactjs?

 <div>
  <img className="icon-arrow" src={icon} role="button" onClick={()=> { // create an animation to rotate the image }} />
</div>
like image 783
Joey Yi Zhao Avatar asked Dec 06 '22 14:12

Joey Yi Zhao


1 Answers

This is the react way to do it.

class Image extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      rotate: false,
      toggle: false
    };
    this.rotatingDone = this.rotatingDone.bind(this);
  }
  componentDidMount() {
    const elm = this.image;
    elm.addEventListener("animationend", this.rotatingDone);
  }
  componentWillUnmount() {
    const elm = this.image;
    elm.removeEventListener("animationend", this.rotatingDone);
  }

  rotatingDone() {
    this.setState(function(state) {
      return {
        toggle: !state.toggle,
        rotate: false
      };
    });
  }
  render() {
    const { rotate, toggle } = this.state;

    return (
      <img
        src={
          toggle
            ? "https://video-react.js.org/assets/logo.png"
            : "https://www.shareicon.net/data/128x128/2016/08/01/640324_logo_512x512.png"
        }
        ref={elm => {
          this.image = elm;
        }}
        onClick={() => this.setState({ rotate: true })}
        className={rotate ? "rotate" : ""}
      />
    );
  }
}

ReactDOM.render(<Image />, document.getElementById("container"));
.rotate {
 animation: rotate-keyframes 1s;
}

@keyframes rotate-keyframes {
 from {
  transform: rotate(0deg);
 }

 to {
  transform: rotate(180deg);
 }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="container">
</div>
like image 186
Tharaka Wijebandara Avatar answered Dec 19 '22 08:12

Tharaka Wijebandara