npm install chart.js
import { Chart as ChartJS, ArcElement, Tooltip, Legend } from "chart.js";
import { Doughnut } from "react-chartjs-2";
ChartJS.register(ArcElement, Tooltip, Legend);
<Doughnut data={...} />
export default function Chart() {
const data = {
labels: ["Red", "Blue", "Yellow"],
datasets: [
{
label: "test",
data: [12, 19, 3],
backgroundColor: ["rgba(255, 99, 132, 0.2)", "rgba(54, 162, 235, 0.2)", "rgba(255, 206, 86, 0.2)"],
borderWidth: 1,
},
],
};
return (
<>
<div style={{ width: "500px", height: "500px", margin: "0 auto" }}>
<Doughnut data={data} options={options} />
</div>
</>
);
}
1.1 그러면 아래와 같은 chart를 얻을 수 있다.
const options = {
plugins: {
legend: {
labels: {
// This more specific font property overrides the global property
font: {
size: 14,
},
},
},
tooltip: {
titleFont: {
size: 12,
},
bodyFont: {
size: 12,
},
footerFont: {
// size: 10, // there is no footer by default
},
callbacks: {
title: () => {
return "title이랑 label 위치 변경!";
},
label: (item) => {
const count = item.dataset.data[item.dataIndex];
const label = item.label;
const info = ` ${label} : ${count}`;
return info;
},
},
},
},
};
// 이하 생략
// <Doughnut data={data} options={options} /> option을 도넛에 넣어주자.
2. 그러면 위 그림과 같이 title
과 lable
위치가 바뀐 걸 볼 수 있다.
3. 여기서 포인트는 callbacks
함수를 활용하여 dataset의 property를 값을 바꿀 수 있다는 점이다.
3.1 예를 들어서 title: () => {return "타이틀 변경"}
처럼 제목을 바꿀 수 있다. 콜백 함수를 잘 활용하자..!
3.2 그리고 콜백 함수에서 console.log()
가 가능하니 인자로 들어온 값을 찍어서 어떤 데이터가 들어오는 지 확인하면 수정하기 더 수월하다. 꿀팁..!
<div>
<Doughnut data={...} />
<ul>
<li>정보 1</li>
<li>정보 2</li>
<li>정보 3</li>
</ul>
</div>
div
에 z-index를 10을 주고 툴팁을 가리는 형제 요소 ul
에 z-index를 -1을 주자.