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

10,533

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"/>
Share:
10,533
Kombo
Author by

Kombo

Updated on June 08, 2022

Comments

  • Kombo
    Kombo almost 2 years

    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.

  • Kombo
    Kombo about 5 years
    I'd also like to add that in case of dealing with material-ui using withStyles() function, the 'styles' obj/function can be described like this: const styles = theme => ({ spinningImg: { animationName: 'spin', animationIterationCount: 'infinite', animationTimingFunction: 'linear', }, '@keyframes spin': { '0%': { transform: 'rotate(0deg)', }, '100%': { transform: 'rotate(360deg)', }, }, });