0

I have a problem where I have made my img rotate in a 360 continously but I want it to only do it when the music is playing. I am passing the value of isPlaying into the function but I do not know how to access the CSS value from React.

import React from "react";

const Song = ({ currentSong, isPlaying }: any) => {
  return (
    <div className="song-container">
      <img id="image" alt={currentSong.name} src={currentSong.cover}></img>
      <h2>{currentSong.name}</h2>
      <h3>{currentSong.artist}</h3>
    </div>
  );
};

export default Song;

This is my CSS file:

.song-container {
  min-height: 70vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  img {
    width: 40%;
    border-radius: 50%;
    animation: spin 10s linear infinite;
    animation-play-state: paused;
  }
  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }
  h2 {
    padding: 3rem 1rem 1rem 1rem;
    font-size: 3rem;
  }
  h3 {
    font-size: 1.5rem;
  }
}

I would just like to be able to stop it when the state is not playing and when it is playing I want the animation to play. I am also using typescript as I want to learn the language but if it is too hard to implement over I will just transition my website over to javascript.

  • I seem to have figured out a solution to the problem using but it is not the prettiest solution, I would love to hear if you guys have a better solution – Sidhant Kaushik Dec 20 '20 at 19:42

1 Answers1

2

There are two ways of doing this: inline styles and toggling some CSS class.

For inline styles method, you should set the style attribute for the img element, and the properties should be in camel case:

<img id="image" alt={currentSong.name} src={currentSong.cover} style={{ animationPlayState: isPlaying ? "running" : "paused" }} />

For the class toggling method, you should create a class in your CSS that changes the animation state.

For example, in the CSS:

img.animate {
  animation-play-state: running;
}

Then, in the img element:

<img id="image" alt={currentSong.name} src={currentSong.cover} className={isPlaying ? "animate" : undefined} />

Toggling classes is a best practice, but both will work and inline styles are better when the styles are based on dynamic values you cannot predict.


Reference: https://reactjs.org/docs/dom-elements.html#style

AqueleHugo
  • 168
  • 6