Skip to content

Instantly share code, notes, and snippets.

@none23
Last active August 2, 2020 21:40
Show Gist options
  • Save none23/9881811145c8ddde5c5ae911ac915229 to your computer and use it in GitHub Desktop.
Save none23/9881811145c8ddde5c5ae911ac915229 to your computer and use it in GitHub Desktop.
import React, { useState } from "react";
import { render } from "react-dom";
import styled from "@emotion/styled";
const Main = styled.main`
font-family: sans-serif;
text-align: center;
color: red;
background: black !important;
height: 100vh;
`;
const Chart = styled.svg`
margin: 0 auto;
border-radius: 50%;
display: block;
`;
const Indicator = styled.circle`
fill: transparent;
stroke-dasharray: 0 10000;
transition: stroke-dasharray 0.3s ease;
`;
const items = [
{ id: 1, v: 20, v1: 20, color: "purple" },
{ id: 2, v: 30, v1: 50, color: "red" },
{ id: 3, v: 40, v1: 90, color: "teal" },
{ id: 4, v: 10, v1: 95, color: "green" }
].map((x, i, a) => ({ ...x, v0: i > 0 ? x.v1 - a[i].v : x.v1 }));
type Props = {
value: number;
label: string;
size: number;
strokewidth: number;
children: React.ReactNode;
};
function DonutChart({ children, value = 0, label = "Completed" }: Props) {
return (
<Chart width="90vmin" height="90vmin" viewBox="0 0 116 116">
{items.reverse().map(({ id, v0, v1, color }, i) => (
<Indicator
key={id}
r={45}
cx={58}
cy={58}
stroke={color}
// transform={`rotate(${i*360} 58,58)`}
strokeWidth={10 - 1 * id}
style={{ strokeDasharray: `${v1 * Math.PI * 0.9} ${Math.PI * 90}` }}
/>
))}
{children}
</Chart>
);
}
function App(): JSX.Element {
const [val, setVal] = React.useState<number>(33.33);
return (
<Main>
<figure>
<DonutChart value={val} />
<figcaption>
Enter a value from 1-100
<br />
<input
onChange={e => setVal(Number(e.currentTarget.value))}
type="number"
min={0}
max={100}
/>
</figcaption>
</figure>
</Main>
);
}
render(<App />, document.querySelector("#root"));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment