리액트에서 Chart.js를 사용하려면 chart.js 뿐만 아니라 리액트에서 Chart.js를 렌더링하기 위해 필요한 react-chartjs-2도 설치를 해야 한다.
yarn add react-chartjs-2 chart.js npm install react-chartjs-2 chart.js
도넛 차트 예시 (공식 문서 예시)
import React from 'react'; import { Chart as ChartJS, ArcElement, Tooltip, Legend } from 'chart.js'; import { Doughnut } from 'react-chartjs-2'; import styled from 'styled-components'; ChartJS.register(ArcElement, Tooltip, Legend); export const data = { labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'], datasets: [ { label: '# of Votes', data: [12, 19, 3, 5, 2, 3], backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)', ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)', ], borderWidth: 1, }, ], }; export default function MyChart() { return ( <Container> <div> <Doughnut data={data} /> <Text> <h1>Doughnut Chart</h1> <a href="https://react-chartjs-2.js.org/examples/doughnut-chart" target="_blank" rel="noreferrer" react-chartjs-2.js.org/examples/doughnut-chart </a> </Text> </div> </Container> ); } const Container = styled.div` width: 100vw; height: 90vh; display: flex; justify-content: center; align-items: center; background-color: black; div { width: 70vw; height: 60vh; padding: 3rem; border-radius: 1rem; background-color: white; display: flex; justify-content: center; align-items: center; } `; const Text = styled.div` display: flex; flex-direction: column; h1 { margin-bottom: 1rem; font-weight: 800; } `;