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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With