Ramlal S
Ramlal S

Reputation: 1643

How to dynamically change animation value in inline syle of ReactJS

I found many related questions regarding inline style of ReactJS but non suitable to mine.

I need to change the animation speed(1,3,4,6,7 are my animation speeds) in UI as per the API values (which changes dynamically)

I tried the following way

<img className="fan1" src={fan1} style={{animation: "spin "`${2}`"s linear infinite" }}></img>    
<img className="fan1" src={fan1} style={{animation: "spin ${2}s linear infinite" }}></img>
<img className="fan1" src={fan1} style={{animation: `spin {2}s linear infinite` }}></img>
<img className="fan1" src={fan1} style={{animation: {spin {2}s linear infinite} }}></img>

I'm not sure how to acheive this. Please help me out.

Upvotes: 2

Views: 88

Answers (2)

Luke Braithwaite
Luke Braithwaite

Reputation: 77

Your main problem is that the style strings are not valid JavaScript. May I suggest reading up on the syntax on template literals. If you change that I suspect it should then work. So your code should look something like this,

<img className="fan1" src={fan1} style={{animation: `spin ${2}s linear infinite` }}></img>    
<img className="fan1" src={fan1} style={{animation: `spin ${2}s linear infinite`  }}></img>
<img className="fan1" src={fan1} style={{animation: `spin ${2}s linear infinite`  }}></img>
<img className="fan1" src={fan1} style={{animation: `spin ${2}s linear infinite`  }}></img>

You loud then replace the ${2} with a link to the state that is constantly being updated.

Upvotes: 1

Ramlal S
Ramlal S

Reputation: 1643

This works for me

<img className="fan1" 
      src={fan1}
      style={{ animation: `spin ${5}s linear infinite` }}
      alt="fan"
  ></img>

Upvotes: 1

Related Questions