본문 바로가기
Programming/Javascript

React에서 Highchart 사용하기 기초 예제

by Wilkyway 2020. 8. 8.
반응형

오늘은 React에서 Highchart 사용하여 아래와 같은 BAR 차트를 한번 그려보려고 합니다. 

1. 설치

우선 create-react-app으로 리액트 환경을 구축하고, Highcharts 와 highcharts-react-official을 설치해 줍니다.

create-react-app .	// '.' 을 입력하면 현재 폴더에 리액트를 설치합니다.
npm install highcharts --save
npm install highcharts-react-official --save

 

2. High.js (Highchart 컴포넌트) 작성

이번 예제에서는 App.js에서 데이터를 props로 전달해주고, Highchart 컴포넌트에서 이를 받아 그래프를 그리도록 구성하겠습니다. 따라서 그래프를 그리는 High.js 를 작성합니다. 

import React, { Component, Fragment } from "react";
import Highcharts from "highcharts";
import HighchartsReact from "highcharts-react-official";

class High extends Component {
    render() {
        const series2 = this.props.data;    //App.js에서 데이터를 보내줄 예정
        const options = {
            chart: {
                type: 'bar'		// bar차트. 아무 설정이 없으면 line chart가 된다.
            },
            title: {
                text: 'My first bar chart'
            },
            credits: {
                enabled: false
            },
            xAxis: {
                type: 'category'
            },
            legend: {
                reversed: true
            },
            plotOptions: {
                series: {
                    stacking: 'normal',
                    dataLabels: {
                        enabled: true,
                        format: "<b>{point.y}</b>",
                    }
                }
            },
            series: [{ name: "data", data: series2 }]

        }
        return (
            <Fragment>
                <HighchartsReact highcharts={Highcharts} options={options} />
            </Fragment>
        );
    }
}
export default High;

 

3. App.js 수정

App.js에서는 위에서 작성한 High.js를 임포트해주고, data를 state로 선언해준 다음 <Highcharts>의 props로 전달해줍니다.

import React, { useState, useEffect, Component } from 'react';
import HighCharts from './High';
import './App.css';


class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: [40000, 50000, 60000, 70000, 80000, 100000, 120000, 150000]
    }
  }
  render() {
    return (
      <div className="App">
        <HighCharts
          data={this.state.data} />
      </div>
    );
  }
}

export default App;

 

실행하면 맨 윗화면처럼 나오게 될 겁니다. 

잘 되시길....행운을 빕니다.

 

(ps) option - type 값을 변경하여 여러가지 차트를 그릴 수 있습니다.

1. type: 'line'

2. type: 'column'

3. type: 'areaspline'

4. type: 'pie'

5. type:'scatter'

- 끝 -

반응형

댓글