In this blog post I am going to talk about how to create a toss effect in React. I took inspiration from this https://codepen.io/designcouch/pen/OJPdZxg which is using jQuery.
Here is the React version:
The idea is to add and remove class from the target element at specific time. For this we use the element classList property. Now to get access to a DOM element in React we use the ref hook called useRef. We use it like this:
const ref = useRef();
then you just add it to the element you want to reference like this:
<span ref={ref} className="cart-item"></span>
then to add or remove a class you we simply do this:
ref.current.classList.add("send-to-cart");
ref.current.classList.remove("send-to-cart");
See the codesandbox above for full code.
