0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Rechartsを使ってグラフ作成

Last updated at Posted at 2022-02-26

前提

以前作成した下記記事の環境からスタートします。

Rechartsの導入

yarn add recharts
yarn add -D @types/recharts

ダミーデータの作成

yarn add -D json-server

mockフォルダ > dummyData.json
dummyData.json

{
"costGraphData": [
    { "date": "01-01", "cost": 1100 },
    { "date": "01-02", "cost": 1200 },
    { "date": "01-03", "cost": 1000 },
    { "date": "01-04", "cost": 800 },
    { "date": "01-05", "cost": 1700 },
    { "date": "01-06", "cost": 1000 },
    { "date": "01-07", "cost": 1000 },
    { "date": "01-08", "cost": 600 },
    { "date": "01-09", "cost": 800 },
    { "date": "01-10", "cost": 400 },
    { "date": "01-11", "cost": 1600 },
    { "date": "01-12", "cost": 1400 },
    { "date": "01-13", "cost": 1100 },
    { "date": "01-14", "cost": 1200 },
    { "date": "01-15", "cost": 900 }
]
}

APIを使ってデータが流れてくる想定でjson-serverを使用し、ダミーデータを作成。
※グラフにしそうなデータを適当に作成

トップレベルのapp.tsxでデータ管理

app.tsx

import React, { useEffect, useState } from "react";

import { CostGraphData } from "./types/type";

const App = () => {
const [graphData, setGraphData] = useState<CostGraphData[]>([]);

useEffect(() => {
    const fetchData = async () => {
    const response = await fetch("http://localhost:3000/costGraphData");
    const data = await response.json();
    setGraphData(data);
    //今回はブラウザ上でデータが入ってきているか確認するためconsoleを記載
    console.log(data);
    };
    fetchData();
}, []);
return (
    <>
    <h1>Hello World</h1>
    </>
);
};
export default App;

src > types > type.d.ts

export interface CostGraphData {
date: string;
cost: number;
}
  • 新たに型をまとめるtype.d.tsファイルを作成

ここまでで確認

まずは、以前作成した記事と同様にfetchでデータが取得できているかの確認

  1. ターミナルでyarn mockを実行
    まとめたscript → ("mock":"npx json-server --watch ./mock/dummyData.json")
  2. 別ターミナルでyarn start
  3. ブラウザでhttp://localhost:8111にアクセスする
  4. 検証のコンソールを開いてデータがあるかの確認

dummyData.jsonで作成したデータと同じ値が表示されていればOK!

グラフの作成

src > componentフォルダ > graph.tsx

import React, { FC } from "react";
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
} from "recharts";

export const CostGraph: FC = () => {

return (
    <LineChart
    width={730}
    height={250}
    data={data}
    margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
    >
    <CartesianGrid strokeDasharray="3 3" />
    <XAxis dataKey="name" />
    <YAxis />
    <Tooltip />
    <Legend />
    <Line type="monotone" dataKey="pv" stroke="#8884d8" />
    <Line type="monotone" dataKey="uv" stroke="#82ca9d" />
    </LineChart>
);
};

型の追加

type.d.ts

export interface CostGraphProps {
costGraphData: CostGraphData[];
}
  • graph.tsxで使う型の作成

データを流す

app.tsx

import React, { useEffect, useState } from "react";
import { CostGraph } from "./component/graph";

import { CostGraphData } from "./types/type";

const App = () => {
const [graphData, setGraphData] = useState<CostGraphData[]>([]);

useEffect(() => {
    const fetchData = async () => {
    const response = await fetch("http://localhost:3000/costGraphData");
    const data = await response.json();
    setGraphData(data);
    };
    fetchData();
}, []);
return (
    <>
    <h1>Hello World</h1>
    <CostGraph costGraphData={graphData} />
    </>
);
};
export default App;

- <CostGraph costGraphData={graphData} />を追加

graph.tsx

import React, { FC } from "react";
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
} from "recharts";

import { CostGraphProps } from "../types/type";

export const CostGraph: FC<CostGraphProps> = (props) => {
const { costGraphData } = props;

return (
    <>
    <LineChart
        width={730}
        height={250}
        data={costGraphData}
        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
    >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="date" />
        <YAxis />
        <Tooltip />
        <Legend />
        <Line type="monotone" dataKey="cost" stroke="#8884d8" />
    </LineChart>
    </>
);
};
  • 公式のAPI部分を見て少しカスタマイズ

最後に

  1. yarn mockと yarn startを実行
  2. ブラウザでhttp://localhost:8111にアクセス

Hello Worldの下にグラフが表示されればOK!

色々なグラフが作れるので試してみてください。

参考文献

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?