React-spring: animate div containing an animated image Code Answer

I’m trying to use react-spring to animate a div and an image inside this div, code below. So far, the dangleProps is working properly: the image is animated, however, the div isn’t: hoveredProps isn’t working for some reason, trying to figure it out:

Icon.js

import React, { useState } from "react";
import { useSpring, animated } from "react-spring";

export const Icon = ({ showPage, imageSource, altText, index }) => {
  const [isHovered, setIsHovered] = useState(false);

  const dangleProps = useSpring({
    transform: showPage ? "rotateZ(0deg)" : "rotateZ(180deg)",
    transformOrigin: "top",
    from: { transform: "rotateZ(180deg)" },
    config: { mass: 1, tension: 210 - index * 50, friction: 5 },
  });

  const hoveredProps = useSpring({
    transform: isHovered ? "rotateZ(320deg)" : "rotateZ(0)",
    from: { transform: "rotateZ(0)" },
    config: { mass: 1, tension: 210, friction: 5 },
  });

  return (
    <animated.div
      className="contact-icon"
      onMouseEnter={() => setIsHovered(true)}
      onMouseLeave={() => setIsHovered(false)}
      style={hoveredProps}
    >
      <animated.img src={imageSource} alt={altText} style={dangleProps} />
    </animated.div>
  );
};


section.contact {
  background-color: rgba(160, 210, 140, 0.3);
  margin: 0;
  height: 100px;
  border-radius: 15px;
  display: flex;
  justify-content: center;
  align-items: center;
}
.contact-icon {
  margin: 0 calc(1vw + 10px);
  cursor: pointer;
}
.contact-icon img {
  height: 50px;
}

Note: section.contact wraps several <Icon />s

Answer

Your example was hard to reproduce. Finally I managed.

The problem is, that you did not specify the unit for the roteteZ. If you add the deg to all of the occurance it will work.

  const hoveredProps = useSpring({
    transform: isHovered ? "rotateZ(320deg)" : "rotateZ(0deg)",
    from: { transform: "rotateZ(0deg)" },
    config: { mass: 1, tension: 210, friction: 5 },
  });

https://codesandbox.io/s/eager-monad-tb41s

Related Posts

© No Copyrights, All Questions are retrived from public domain.
Tutorial Guruji