Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a simple spinning animation for an image in React

I'm using reactjs with material-ui styling, to create a dapp and have an image (circular in shape) which i want to spin continuously which customizable spin speed, maintaining a smooth flow. The spin speed needs to be customizable in which i feed a speed value to the component and it'd spin in that speed accordingly. Any ideas how to go by? Thanks.

PS: this is not related to 'loading components', loading animation, or loading image in any way. also, a solution which can be implemented using withStyles() of material-ui would be preferred. Thanks.

like image 967
Kombo Avatar asked Feb 19 '19 03:02

Kombo


Video Answer


1 Answers

I'm writing this answer with respect to my comments above:

First, define a css animation keyframe to do a spin:

@keyframes spin {
  from {transform:rotate(0deg);}
  to {transform:rotate(360deg);}
}

Next, in your constructor, define the speed value:

constructor(props) {
 super(props);
 this.state = {
  speed: 3
 }
}

finally, make use of inline styling in ReactJS to pass a custom speed value from state (or sth like this.props.customSpdProps if you want to pass from props):

<img style={{animation: `spin ${this.state.speed}s linear infinite`}} src={SampleImg} alt="img"/>
like image 65
Andus Avatar answered Oct 11 '22 00:10

Andus