Search code examples
javascriptreactjscss-animationscodepen

ClassList toggling not working in React. What am I doing wrong?


I'm trying to get a wheel image to spin (CSS transform + transition) when it is clicked. Right now, I can only get it to spin while holding the mouse button using img: active. I've looked for answers and generally get the sense that I should just use onClick to toggle a class with the animation on and off, but I don't seem to be doing it right. What am I doing wrong? Here's my code for reference:

class Wheel extends React.Component
{
  constructor(props){
    super(props);

    this.spin = this.spin.bind(this);
  }
  
  spin(e){
    e.classList.toggle('rotate');      
  }

  render(){
    return (<div><img width="400" height="400" src="https://orig00.deviantart.net/0a38/f/2010/242/f/6/singapore_wheel_of_fortune_by_wheelgenius-d2xmb9v.jpg" onClick={this.spin}/>
</div>);    
  }
}

ReactDOM.render(
  <Wheel/>,
  document.getElementsByClassName('container-fluid')[0]
);

CSS:

.rotate {
  -webkit-transform: rotate(1095deg);
  -webkit-transition: -webkit-transform 3s ease-out;
}

/* 
img:active {
  -webkit-transform: rotate(1095deg);
  -webkit-transition: -webkit-transform 3s ease-out;
}
*/

I've also put everything on a CodePen.


Solution

  • The e parameter to your event handler is the event that was triggered, not the node. The target node is e.target so your code should be

    e.target.classList.toggle('rotate');