Search code examples
reactjsanimationsvgtransition

Firefox does not animate when <g> component attributes change


I'm creating some animated React components in SVG. When I run it in Chrome, the animation works, but when I run it in Firefox, it doesn't.

Here is an example:

const [x, setX] = useState(0)

useEffect(() => {
  setTimeout(() => {
    setX(100)
  }, 3000)
}, [])

return (
  <svg width={500} height={300}>
    <g transform={`translate(${x}, ${0})`} style={{ transition: "3s all" }}>
      <rect width={50} height={50} x={0} y={0} fill={'#f00'} />
    </g>
  </svg>
)

You can see that it works in Chrome, but not in Firefox: https://codesandbox.io/s/gracious-ives-ykmfp

If I remove the transform in g and change direct in x prop of the rect, that way will work in Firefox, but I don't want to do it that way.

Any help?


Solution

  • The transform attribute is not the same as the transform CSS property, even though it can be confusing (and apparently the two will be merged).

    Instead of using the attribute, move the transform to the style property:

    const [x, setX] = useState(0);
    
    useEffect(() => {
      setTimeout(() => {
        setX(100);
      }, 3000);
    }, []);
    
    return (
      <svg width={500} height={300}>
        <g style={{ transform: `translate(${x}px, 0px)`, transition: 'all 3s' }}>
          <rect width={50} height={50} x={0} y={0} fill={'#f00'} />
        </g>
      </svg>
    );
    

    Demo: https://codesandbox.io/s/nifty-snowflake-664rk