Search code examples
reactjsscopecss-transforms

I'm having a difficult time trying to find a place to put a function that transforms a rendered component in React


I've been stuck for a day and a half moving a function around to try to transform the style of a component to place each card in a deck rotated. The cards are rotating, but the previously rendered cards have their rotated values change on every re-render. Can anyone point me in the right direction? Thank you, and please forgive the bowl of spaghetti you're gonna find if you look at the sandbox.

My Code Sandbox

import React, {useState} from "react";
import "./Card.css";

function Card(props) {

  function animateCard(){
    let angle = Math.random() * 90 - 45;
    let xPos = Math.random() * 40 - 20;
    let yPos = Math.random() * 40 - 20;
    let transform = `translate(${xPos}px, ${yPos}px) rotate(${angle}deg)`;
    return transform;
  }
 
  return (
    <div className="Card-container">
      <img
        className="Card"
        style={{ transform:animateCard()}}
        src={props.image}
        alt={props.name}
      />
    </div>
  );
}

export default Card;


Solution

  • The rotated values for previously rendered cards are changing on each re-render because the animateCard function is within the 'Card' component and is being called on each re-render.

    You should put the animateCard function in the CardDeck component and whenever you get a new card, call the animateCard function to get the transform properties(angle, xPos, yPos), then save the transform properties for each card into the card state with setCard. Then, you'll pass that tranform property as a prop into the Card component. This ensures that once that property is generated and saved, it won't be generated again on each re-render.

    Here's a functioning sandbox