Dev Helpers
← Back

Regular polygon builder

Import and render <RegularPolygonBuilder /> in a React project.

Open this example in the interactive library

Live preview

Source code

// components/RegularPolygonBuilder.tsx

import { useState } from "react";

export default function RegularPolygonBuilder({ width = 12 }: { width?: number } = {}) {
  const [n, set] = useState(5);
  const points = Array.from({ length: n }, (_, i) =>
    [
      50 + 45 * Math.cos((2 * Math.PI * i) / n),
      50 + 45 * Math.sin((2 * Math.PI * i) / n),
    ].join(","),
  ).join(" ");
  return (
    <label>
      Sides
      <input
        type="range"
        min={3}
        max={12}
        value={n}
        onChange={(e) => set(+e.target.value)}
      />
      <svg
        viewBox="0 0 100 100"
        width="100"
        aria-label={n + " sided polygon"}
        role="img"
      >
        <polygon points={points} />
      </svg>
    </label>
  );
}