[React Chart] 리액트 chartjs legend custom 하기

2023. 4. 24. 22:59·Frontend/React
목차
  1. 참고 문서

참고 문서

https://www.chartjs.org/docs/latest/samples/legend/html.html

 

HTML Legend | Chart.js

HTML Legend This example shows how to create a custom HTML legend using a plugin and connect it to the chart in lieu of the default on-canvas legend. const getOrCreateLegendList = (chart, id) => { const legendContainer = document.getElementById(id); let li

www.chartjs.org

https://www.chartjs.org/docs/latest/developers/plugins.html

 

Plugins | Chart.js

Plugins Plugins are the most efficient way to customize or change the default behavior of a chart. They have been introduced at version 2.1.0 (opens new window) (global plugins only) and extended at version 2.5.0 (opens new window) (per chart plugins and o

www.chartjs.org

https://react-chartjs-2.js.org/components/line

 

Line | react-chartjs-2

Description of Line component from react-chartjs-2.

react-chartjs-2.js.org

 

리액트에서 Line 컴포넌트 plugins 프롭스에 custom legend 함수 작성해주면된다.

<Line
  options={options}
  data={data}
  plugins={[htmlLegendPlugin]}
/>

 

콘솔로 찍어가면서 html 생성해주고, css로 마무리하면된다.

const getOrCreateLegendList = (chart, id) => {
  const legendContainer = document.getElementById(id);
  let listContainer = legendContainer.querySelector('ul');

  if (!listContainer) {
    listContainer = document.createElement('ul');
    listContainer.style.display = 'flex';
    listContainer.style.flexDirection = 'row';
    listContainer.style.margin = 0;
    listContainer.style.padding = 0;

    legendContainer.appendChild(listContainer);
  }

  return listContainer;
};

const htmlLegendPlugin = {
  id: 'htmlLegend',
  afterUpdate(chart, args, options) {
    const ul = getOrCreateLegendList(chart, options.containerID);

    // Remove old legend items
    while (ul.firstChild) {
      ul.firstChild.remove();
    }

    // Reuse the built-in legendItems generator
    const items = chart.options.plugins.legend.labels.generateLabels(chart);

    items.forEach(item => {
      const li = document.createElement('li');
      li.style.alignItems = 'center';
      li.style.cursor = 'pointer';
      li.style.display = 'flex';
      li.style.flexDirection = 'row';
      li.style.marginLeft = '10px';

      li.onclick = () => {
        const {type} = chart.config;
        if (type === 'pie' || type === 'doughnut') {
          // Pie and doughnut charts only have a single dataset and visibility is per item
          chart.toggleDataVisibility(item.index);
        } else {
          chart.setDatasetVisibility(item.datasetIndex, !chart.isDatasetVisible(item.datasetIndex));
        }
        chart.update();
      };

      // Color box
      const boxSpan = document.createElement('span');
      boxSpan.style.background = item.fillStyle;
      boxSpan.style.borderColor = item.strokeStyle;
      boxSpan.style.borderWidth = item.lineWidth + 'px';
      boxSpan.style.display = 'inline-block';
      boxSpan.style.height = '20px';
      boxSpan.style.marginRight = '10px';
      boxSpan.style.width = '20px';

      // Text
      const textContainer = document.createElement('p');
      textContainer.style.color = item.fontColor;
      textContainer.style.margin = 0;
      textContainer.style.padding = 0;
      textContainer.style.textDecoration = item.hidden ? 'line-through' : '';

      const text = document.createTextNode(item.text);
      textContainer.appendChild(text);

      li.appendChild(boxSpan);
      li.appendChild(textContainer);
      ul.appendChild(li);
    });
  }
};
반응형

'Frontend > React' 카테고리의 다른 글

[Yarn] react에서 yarn berry (pnp) 에러  (0) 2023.05.04
[React] 리액트 range slider 라이브러리 사용해서 range bar 만들기  (0) 2023.04.26
[React Chart] 리액트 chart.js tooltip custom 하기  (0) 2023.04.24
[React Swiper] loop={true} 마지막 페이지 먼저보이는 에러  (0) 2023.04.13
[React Swiper] import css 안될 때  (0) 2023.04.13
  1. 참고 문서
'Frontend/React' 카테고리의 다른 글
  • [Yarn] react에서 yarn berry (pnp) 에러
  • [React] 리액트 range slider 라이브러리 사용해서 range bar 만들기
  • [React Chart] 리액트 chart.js tooltip custom 하기
  • [React Swiper] loop={true} 마지막 페이지 먼저보이는 에러
전예방
전예방
예방이의 개발일기전예방 님의 블로그입니다.
  • 전예방
    예방이의 개발일기
    전예방
  • 전체
    오늘
    어제
    • All (125)
      • Info & Tip (2)
      • 유용한 사이트들 (5)
      • Mark Up & StyleSheet (23)
        • HTML (6)
        • CSS & SCSS (10)
        • 반응형 (6)
      • Frontend (66)
        • 전체 (10)
        • JavaScript & Jquery (18)
        • TypeScript (0)
        • React (26)
        • Next.js (3)
        • 성능최적화 (2)
        • 웹접근성 (2)
      • Backend (13)
        • Python (1)
        • JAVA (2)
        • node.js (0)
        • PHP (7)
        • 패키지매니저 (3)
      • Markdown (0)
      • SCM (1)
        • Git&Github (1)
        • SVN (0)
      • IDE (4)
        • VSCode (2)
        • IntelliJ (1)
        • Ecplise (1)
      • 취미생활 (3)
      • 정보처리기사 (2)
      • 코딩자율학습단 (5)
        • 12기 (파이썬) (5)
  • 블로그 메뉴

    • 홈
    • 태그
  • 링크

    • velog
    • github
  • 공지사항

  • 인기 글

  • 태그

    swiper.js
    반응형
    TypeScript
    yarn berry
    관리자 페이지
    파이썬
    Admin
    회원가입
    react
    Chart.js
    React Swiper
    NPM
    나도코딩
    CSS
    코딩자율학습
    php
    리액트
    Python
    코딩자율학습단
    frontend
  • 최근 댓글

  • 최근 글

  • 반응형
  • hELLO· Designed By정상우.v4.10.3
전예방
[React Chart] 리액트 chartjs legend custom 하기

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.