Welcome folks today in this blog post we will be building a bmi calculator
using weight and height in react.js hooks.
All the full source code of the application is shown below.
Get Started
First of all install the chart.js
library by the following command
npm i chartjs
And now if you create an App.jsx
file and copy paste the following code
App.jsx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
import React, { useState, useEffect } from 'react'; import { v4 as uuidv4 } from 'uuid'; import 'materialize-css/dist/css/materialize.min.css'; import './App.css'; import BmiForm from '../BmiForm/BmiForm'; import Info from '../Info/Info'; import Bar from '../Bar/Bar'; import { getData, storeData } from '../../helpers/localStorage'; const App = () => { const initialState = () => getData('data') || []; const [state, setState] = useState(initialState); const [data, setData] = useState({}); useEffect(() => { storeData('data', state); const date = state.map(obj => obj.date); const bmi = state.map(obj => obj.bmi); let newData = { date, bmi }; setData(newData); }, [state]); const handleChange = val => { let heightInM = val.height / 100; val.bmi = (val.weight / (heightInM * heightInM)).toFixed(2); val.id = uuidv4(); let newVal = [...state, val]; let len = newVal.length; if (len > 7) newVal = newVal.slice(1, len); setState(newVal); }; const handleDelete = id => { storeData('lastState', state); let newState = state.filter(i => { return i.id !== id; }); setState(newState); }; const handleUndo = () => { setState(getData('lastState')); }; return ( <div className='container'> <div className='row center'> <h1 className='white-text'> BMI Tracker </h1> </div> <div className='row'> <div className='col m12 s12'> <BmiForm change={handleChange} /> <Bar labelData={data.date} bmiData={data.bmi} /> <div> <div className='row center'> <h4 className='white-text'>7 Day Data</h4> </div> <div className='data-container row'> {state.length > 0 ? ( <> {state.map(info => ( <Info key={info.id} id={info.id} weight={info.weight} height={info.height} date={info.date} bmi={info.bmi} deleteCard={handleDelete} /> ))} </> ) : ( <div className='center white-text'>No log found</div> )} </div> </div> {getData('lastState') !== null ? ( <div className='center'> <button className='calculate-btn' onClick={handleUndo}> Undo </button> </div> ) : ( '' )} </div> </div> </div> ); }; export default App; |
In order to get started you need to install the full source code
of the application
by the below link
Now if you run the following react.js project
you will see the following result