tangway / flag-guessing-game-frontend

0 stars 0 forks source link

trigger animation of flag on user making the selection #6

Open tangway opened 5 months ago

tangway commented 5 months ago

to trigger the animation of the flag on user's selection, a prop would need to be passed from App.jsx to AnimatedComponent so that AnimatedComponent knows when to start animating.

AnimatedComponent is a Higher Order Component (HOC) that i wrote earlier when figuring out how to standardize framer motion animation parameters across all flags displayed. it is used like so: const FlagComponent = AnimatedComponent(svgFlagComponent)

startAnimation state is added and then used as a prop that is passed to the FlagComponent

const [startAnimation, setStartAnimation] = useState(false)
...
<FlagComponent startAnimation={startAnimation} />

then in AnimatedComponent it is wrapped by useEffect so that it can trigger the animation whenever the state of startAnimation changes to true:

const AnimatedComponent = Component => ({ startAnimation, ...props }) => {
  const controls = useAnimation();

  useEffect(() => {
    if (startAnimation) {
      controls.start({
        opacity: 1,
      });
    } else {
      controls.set({
        opacity: 0,
      });
    }
  }, [startAnimation]);
...

so when the user clicks on the selection and triggers the checkAnswer function it changes the startAnimation function to true the FlagComponent will re-render and animate the flag!

const checkAnswer = userSelection => {
    if (userSelection === correctAnswer) {
      setCorrect(true);
    } else {
      setCorrect(false);
    }

    setStartAnimation(true);
  };