Frontend/Apache Echarts

[echarts] Apache Echarts 에 click event 적용하기

Dogvelop 2023. 9. 22. 15:17

heatmap, line chart 등 다양한 chart를 만들고 난 뒤 해당 chart의 특정 point, cell 등을 click하여 현재 본인이 선택한 state를 얻고 싶을 때가 있다.

ex ) line chart에서 내가 click 한 특정 point 강조하기, heatmap의 click한 cell 하나 강조하기 ...

 

React + Typescript 환경에서의 코드이다.

const [nowIndex, setNowIndex] = useState(undefined);

useEffect(() => {
    if (chartRef.current) {
      const chart = echarts.init(chartRef.current);

      // 정해진 option이 있다고 가정한다.
      chart.setOption(option);
      
      chart.on("click", function (params) {
        // params에서 현재 내가 click한 data의 자세한 정보를 가져올 수 있다.
        // 이를 이용해서 원하는 방법으로 customizing
        // ex) line chart일 경우 nowIndex란 state를 click한 data의 index로 변경
        if (params.seriesType === "line") setNowIndex(params.dataIndex);
      });
      
    }
}, [option, chartRef, setNowTimeIndex]);

return (
    <div className={styles.component}>
      <div ref={chartRef} style={{ height: 250 }} />
    </div>
);

이와 같이 chart.on("click" , ... ) 을 통해 click event를 감지하고 원하는대로 customizing이 가능하다.