フリーランス 技術調査ブログ

フリーランス/エンジニア Ruby Python Nodejs Vuejs React Dockerなどの調査技術調査の備忘録

ReactHooksでBMI計算で1日ごとの結果をグラフに表示する(chatjs使用)

はじめに

  • ReactHooksでBMI計算で1日ごとの結果を一覧で表示する(redux/useContext使用)を作成したので、そのデータをグラフで表示してみる。  下記のサンプルは下記の過去記事を続きの実装となります。

  • 利用したパッケージは下記の2つとなります。

yarn add react-chartjs-2 chat.js

実装コード

  • components/bmi/BmiLine.jsファイルはグラフ表示部分
import React,{useState, useContext} from 'react'
import {Line} from 'react-chartjs-2';
import moment from 'moment'

import AppContext from '../../contexts/AppContext'


const BmiLine = () => {
  const {state, dispatch } = useContext(AppContext)

  const labelData = [...Array(14)].map((_, i) => moment().add('days', -i).format("YYYY-MM-DD") ) 
  labelData.sort()

  const oustputBmiData = labelData.map(date => {
    const bmi = state.bmis.filter(bmi => bmi.measurementDate === date)
    return bmi.length === 0 ? null : bmi[0].resultBmi
  })

  const oustputWeightData = labelData.map(date => {
    const bmi = state.bmis.filter(bmi => bmi.measurementDate === date)
    return bmi.length === 0 ? null : bmi[0].bodyWeight
  })

  const data = {
    labels: labelData,
    datasets: [
      {
        fill: true,
        lineTension: 0.1,
        backgroundColor: 'rgba(75,192,192,0.4)',
        borderColor: 'rgba(75,192,192,1)',
        borderCapStyle: 'round',
        borderDash: [],
        borderDashOffset: 0.0,
        borderJoinStyle: 'square',
        pointBorderColor: 'rgba(75,192,192,1)',
        pointBackgroundColor: '#eee',
        pointBorderWidth: 10,
        pointHoverRadius: 5,
        pointHoverBackgroundColor: 'rgba(75,192,192,1)',
        pointHoverBorderColor: 'rgba(220,220,220,1)',
        pointHoverBorderWidth: 1,
        pointRadius: 1,
        pointHitRadius: 10,
        label: 'BMI',
        data: oustputBmiData,
      },
      {
        label: '体重',
        fill: true,
        lineTension: 0.1,
        backgroundColor: 'rgba(244,194,137,0.4)',
        borderColor: 'rgba(244,194,137,1)',
        borderCapStyle: 'round',
        borderDash: [],
        borderDashOffset: 0.0,
        borderJoinStyle: 'square',
        pointBorderColor: 'rgba(244,194,137,1)',
        pointBackgroundColor: '#eee',
        pointBorderWidth: 10,
        pointHoverRadius: 5,
        pointHoverBackgroundColor: 'rgba(244,194,137,1)',
        pointHoverBorderColor: 'rgba(220,220,220,1)',
        pointHoverBorderWidth: 1,
        pointRadius: 1,
        pointHitRadius: 10,        
        data: oustputWeightData
      }
    ]
  };

  return (
    <div>
      <h2>BMI・体重推移</h2>
      <Line data={data} />
    </div>
  );
}

export default BmiLine;

作成した画面イメージ

  • 下記のデータをもとにグラフを表示する f:id:PX-WING:20200603001653p:plain

  • グラフ出力結果 f:id:PX-WING:20200603001741p:plain