FunnyO
FunnyO

Reputation: 403

Dynamically draw/turn SVG with variable input

I want to dynamically draw/turn an SVG with React from degree paramters that im recieving. Its like the direction arrow from a weather-info. enter image description here

  1. How do I dynamically draw an SVG in Javascript / ReactJS?
  2. How do I turn the SVG with variable input?

I'm aware, that you can draw SVG-Graphics like this:

function draw_square() {
    var draw = SVG('square_1');
    draw.size(120, 120);
    var square = draw.rect(100, 100);
    square.attr({ fill: '#f06' });
}
 
draw_square()

but how do I connect different svg-paths to each other?

Upvotes: 1

Views: 980

Answers (1)

bas
bas

Reputation: 15722

I recommend a slightly different approach:

const WindDirectionIcon = ({ width, height }) => {
  return (
    <svg
      id="wind-direction-arrow"
      width={width}
      height={height}
      viewBox="0 0 12 12"
      fill="none"
      xmlns="http://www.w3.org/2000/svg"
    >
      <path d="M6 0L0 12L6 9L12 12L6 0Z" fill="black" />
    </svg>
  );
};

export default function App() {
  useEffect(() => {
    const degrees = 90; // Retrieve from your API
    const arrow = document.getElementById("wind-direction-arrow");
    arrow.setAttribute("transform", `rotate(${degrees})`);
  }, []);

  return (
    <div className="App">
      <WindDirectionIcon width="24" height="24" />
    </div>
  );
}

So the svg itself can be composed of a single path and the only thing we do with javascript is to set the transform attribute to rotate a certain number of degrees based on the API data you receive using template literals.

Rotate with javascript based on this answer.

Sandbox Example

Upvotes: 1

Related Questions