cssreactjsanimationflipcard

Flipping a card, CSS animation for web app


I've managed to build a card in React with a front and backside and have it flip successfully on hover with CSS. However, I want to flip it on click/touch.

I tried setting the transform property to a class and toggling that class on click but no luck.

How would you accomplish this?

This is how I am currently flipping it via hover:

.card {
  position: relative;
  perspective: 800px;
  transition: transform 1s ease;
  perspective: 1000px;
} 
 
.card > * {
  width: 10rem;
  transition: transform 1s ease;
  backface-visibility: hidden;
}

.card:hover > .card__front {
transform: rotateY(180deg);
}

.card:hover > .card__back {
transform: rotateY(0);
}

and my JSX

        <div className={styles.card} >
          {/* FRONTSIDE */}
            <div className={styles.card__front}>
              //FRONTSIDE CONTENT
            </div>

            {/* BACKSIDE */}
            <div className={styles.card__back}>
               //BACKSIDE CONTENT
            </div>
        </div>

UPDATE

This function works, it toggles the flip class on and off on my desired element. However, no animation happens once the class is added. The .flip class does the exact same thing as the :hover did though..

 //function to toggle class
 const flip = (element) => {
    console.log(element);
    element.classList.toggle("flip");
  };

//the css class
.flip {
  transform: rotateY(180deg);
}

  

Solution

  • The problem was that React won't rerender the DOM when a class is added with the .toggle method.

    The solution was to create a state out of the classlist and add the class from the classlist by using the setState method. This triggers a rerender

    //JS
    const [classlist, setClasslist] = useState(styles.card)
    
    const flip = () => {
    setClasslist(classlist + styles.flip)
    }
    
    //HTML
    <div className={classlist} onClick={() => flip()}>