Home > OS >  change css property with onClick function on React
change css property with onClick function on React

Time:03-12

I have this code on css:

.coin {
    height: var(--coin-size);
    width: var(--coin-size);
..(blablabla)
}

.coin::before {
..(blablabla)
    animation: spin 5s linear infinite;
..(blablabla)
}

And this code on the JS :

   <div className="col-sm" id="coinId">
              <div className="coin" onClick={coinSpin}></div>
            </div>

What should I put in the coinSpin function so that it will decrease the animation: spin 5s linear infinite by 0.5 on every click?

I cannot understand how to access this attribute on the CSS..

Thank you :)

CodePudding user response:

You can use in-line styling & trigger that styles when the user clicks, or you have an option to use classNames package.

CodePudding user response:

If you are changing simple stuff in the CSS via state you could add a class to the element you want to modify which will contain the different properties and values. So for example...

.coin {
  color: blue;
}

.coin.spin::before {
  animation: spin 5s linear infinite
}

The .coin.spin syntax is targeting all the .coin elements that contain the .spin class. So by adding and remove that class you are making your coin...spin.

In your onSpin function you'll add the class and then use setTimeout for 5000 miliseconds and then automatically remove the class.

  • Related