import { useEffect, useRef } from 'react';
import { Doughnut } from 'react-chartjs-2';
import styled from '@emotion/styled';
import { DashboardData } from '~/interfaces/Dashboard';
import { ArcElement, Chart as ChartJS, Legend, Tooltip } from 'chart.js';
import { toPng } from 'html-to-image';
ChartJS.register(ArcElement, Tooltip, Legend);
interface Props {
items: DashboardData[];
}
function DonutChart({ items }: Props) {
const chartRef = useRef(null);
const handleDownloadClick = () => {
if (chartRef.current !== null) {
toPng(chartRef.current).then((dataUrl) => {
const link = document.createElement('a');
link.download = 'chart.png';
link.href = dataUrl;
link.click();
});
}
};
useEffect(() => {
console.log(items);
}, []);
const data = {
labels: items.map((item) => item.name),
datasets: [
{
label: '#count',
data: items.map((item) => item.count),
backgroundColor: items.map((item) => item.hex),
borderWidth: 1,
},
],
};
return (
<>
<ChartContainer ref={chartRef}>
<Doughnut data={data} />
</ChartContainer>
<Button onClick={handleDownloadClick}>다운로드</Button>
</>
);
}
export default DonutChart;
const ChartContainer = styled.div`
align-item: center;
width: 500px;
background-color: white;
height: 500px;
`;
const Button = styled.button`
width: 100px;
height: 45px;
font-size: 10px;
border-radius: 10px;
`;
만들어진 도넛차트 이미지를 다운로드하려면..
import html-to-image from 'html-to-image' 가 아니라
import {toPng} from 'html-to-image' 를 해야한다.
html-to-image 라이브러리가 기본 내보내기(default export)를 제공하지 않아서 {topng}로 특정해야 한단다.
'프론트엔드 > 리액트' 카테고리의 다른 글
리액트로 json server 만들기 (1) | 2023.04.20 |
---|---|
리액트로 도넛모양차트 하이차트, +annotation 옵션 구현 (0) | 2023.04.13 |
Mac에서 nginx로 리액트 배포 (0) | 2023.04.03 |
useQuery에서 staleTime과 keepPreviousData 차이 (0) | 2023.03.06 |
리액트로 년, 연, 일 Date출력 toLocaleString 활용 (0) | 2023.02.15 |