Search code examples
csssvgrotationcss-transformsstyled-components

Trying to "transform: rotate()" a <circle> element using styled-components


CodeSandbox with example:

https://codesandbox.io/s/floral-surf-l7m0x

I'm trying to rotate 180º a circle element inside an SVG. I'm being able to do it with the regular <circle> tag, but I'm not being able to do it with the styled component styled.circle

LS.Svg_SVG = styled.svg`
  border: 1px dotted silver;
  width: 100px;
  height: 100px;
`;

LS.Circle_CIRCLE = styled.circle`
  stroke-dasharray: 289.0272;
  stroke-dashoffset: -144.5136;
  transform: rotate(180 50 50);             /* <------------ IT DOES NOT WORK */
`;

export default function App() {
  return (
    <React.Fragment>
      <LS.Container_DIV>
        <LS.Svg_SVG viewBox="100 100">
          <circle                            /* USING REGULAR <circle> */
            cx="50"
            cy="50"
            r="46"
            stroke="black"
            strokeWidth="8px"
            fill="none"
            strokeDasharray="289.0272"
            strokeDashoffset="-144.5136"
            transform="rotate(180 50 50)"   /* <----------------- IT WORKS */
          />
        </LS.Svg_SVG>
      </LS.Container_DIV>
      <LS.Container_DIV>
        <LS.Svg_SVG viewBox="100 100">
          <LS.Circle_CIRCLE                 /* USING STYLED COMPONENTS */
            cx="50"
            cy="50"
            r="46"
            stroke="black"
            strokeWidth="8px"
            fill="none"
          />
        </LS.Svg_SVG>
      </LS.Container_DIV>
    </React.Fragment>
  );
}

The result I'm getting:

enter image description here

They both should be the same. The first one is rotated (using regular <circle>). The second one is not rotated (using styled-components). Even though I'm setting transform: rotate(-180 50 50); in the styled component.


Solution

    1. In CSS, units are required (ie. 180deg, 50px)
    2. The SVG-specific version of rotate: rotate(angle, cx, cy), is not supported in the CSS version of transform. You'll need to use transform-origin.

      LS.Circle_CIRCLE = styled.circle`
        stroke-dasharray: 289.0272;
        stroke-dashoffset: -144.5136;
        transform: rotate(180deg);
        transform-origin: 50px 50px;
      `;