React/TypeScript/chart.js 메모

React 프로젝트 만들기


$ npx create-react-app sample --template typescript

axios 및 chart.js 설치


$ cd sample
$ npm install axios
$ npm install --save react-chartjs-2 chart.js 

로컬 서버 시작


$ npm start

구현



sample/src/components/GetCovid19.tsx
import React, {useState, useEffect} from 'react'
import axios from 'axios'
import datajson from './data.json'
import { Line } from 'react-chartjs-2'

type DATATYPE = typeof datajson 

const GetCovid19 = () => {
    const [covid19s, setCovid19s] = useState<DATATYPE>([])

    useEffect(() => {
        axios.get<DATATYPE>('https://api.covid19api.com/dayone/country/japan').then(res => { setCovid19s(res.data) })
    }, [])

    const data = {
        labels: covid19s.map(covid19 => new Date(covid19.Date).toDateString()),
        datasets: [
            {
                label: 'Confirmed',
                data: covid19s.map(covid19 => covid19.Confirmed),
                borderColor: 'blue'
            },
            {
                label: 'Recovered',
                data: covid19s.map(covid19 => covid19.Recovered),
                borderColor: 'green'
            },
             {
                label: 'Deaths',
                data: covid19s.map(covid19 => covid19.Deaths),
                borderColor: 'red'
            },
        ]
    }

    return (
        <div>
            <Line data={data}/>
        </div>
    )
}

export default GetCovid19

sample/src/App.tsx
import React from 'react';
import logo from './logo.svg';
import './App.css';
import GetCovid19 from './components/GetCovid19';

function App() {
  return (
    <div className="App">
      <GetCovid19 />
    </div>
  );
}

export default App;

좋은 웹페이지 즐겨찾기