FE/React
리액트 구글 차트 사용법 (react google charts 라이브러리)
시녜's
2023. 5. 8. 13:03
1. 구글 차트 라이브러리 설치 - yarn 또는 npm 사용
npm install react-google-charts
yarn add react-google-charts
* 구글 차트 사용법 - 홈페이지 참고
Examples | React Google Charts
List of react-google-charts usage examples.
www.react-google-charts.com
2. chart 컴포넌트를 import 한다
import { Chart } from "react-google-charts";
3. 데이터 가져오는 getData 함수 작성, 상태변수 data를 생성해 결과를 담아준다
const [data,setData] = useState([]);
const getData = async() =>{
const result = await axios.get("/chart1?yy=2023");
let rows = [["년월","게시글수","댓글수","회원가입수"]];
result.data.forEach(item=>{
let row = [item.yymm,item.post_count,item.comment_count,item.user_count];
rows.push(row);
});
setData(rows);
}
- rows 배열 생성해서 필드명을 담아준다.
- axios를 통해 가져온 데이터는 결과의 data에 들어있으며 forEach로 반복하여 row변수를 생성해 각각의 필드값을 담아준다.
- 반복해서 넣은 각각의 데이터 row를 rows배열에 추가한 뒤 data변수에 담아준다.
4. useEffect 훅으로 렌더링 할 때 getData함수 호출
useEffect(()=>{
getData();
},[]);
5. 차트 옵션 데이터 변수 생성
const options = {
chart: {
title: "년도별 게시글, 댓글수"
},
};
- 차트의 타이틀을 넣어주었다.
6. return문 안에서 차트 데이터 출력
- 위에서 import한 chart컴포넌트 안에 각각의 옵션을 담아준다
return (
<Row>
<Col>
<Chart
chartType="Bar"
width="100%"
height="400px"
data={data}
options={options}
/>
</Col>
</Row>
)