|
| 1 | +import React, { useMemo, useState } from 'react'; |
| 2 | + |
| 3 | +import './styles/styles.css'; |
| 4 | +import CalculatorForm from './components/CalculatorForm'; |
| 5 | +import ResultDisplay from './components/ResultDisplay'; |
| 6 | + |
| 7 | +import { calculateBMR, calculateTDEE } from './utils/healthUtils'; |
| 8 | +import { FormData } from './types'; |
| 9 | + |
| 10 | +const BodyCompositionCalculator: React.FC = () => { |
| 11 | + const [formData, setFormData] = useState<FormData>({ |
| 12 | + gender: 'male', |
| 13 | + weight: '', |
| 14 | + height: '', |
| 15 | + age: '', |
| 16 | + activityLevel: 'sedentary' |
| 17 | + }); |
| 18 | + |
| 19 | + /** |
| 20 | + * Generic handler for updating form state |
| 21 | + */ |
| 22 | + const handleChange = (field: keyof FormData, value: string) => { |
| 23 | + setFormData((prev) => ({ |
| 24 | + ...prev, |
| 25 | + [field]: value |
| 26 | + })); |
| 27 | + }; |
| 28 | + |
| 29 | + /** |
| 30 | + * Convert Inputs Safely |
| 31 | + */ |
| 32 | + const numericWeight = Number(formData.weight); |
| 33 | + const numericHeight = Number(formData.height); |
| 34 | + const numericAge = Number(formData.age); |
| 35 | + |
| 36 | + const isValid = numericWeight > 0 && numericHeight > 0 && numericAge > 0; |
| 37 | + |
| 38 | + /** |
| 39 | + * Derived BMR |
| 40 | + */ |
| 41 | + const bmr = useMemo(() => { |
| 42 | + if (!isValid) return null; |
| 43 | + |
| 44 | + return calculateBMR({ |
| 45 | + gender: formData.gender, |
| 46 | + weight: numericWeight, |
| 47 | + height: numericHeight, |
| 48 | + age: numericAge |
| 49 | + }); |
| 50 | + }, [formData.gender, numericWeight, numericHeight, numericAge, isValid]); |
| 51 | + |
| 52 | + /** |
| 53 | + * Derived TDEE |
| 54 | + */ |
| 55 | + const tdee = useMemo(() => { |
| 56 | + if (!bmr) return null; |
| 57 | + |
| 58 | + return calculateTDEE(bmr, formData.activityLevel); |
| 59 | + }, [bmr, formData.activityLevel]); |
| 60 | + |
| 61 | + return ( |
| 62 | + <div className="container"> |
| 63 | + <h2 className="calculator-title">BMR & TDEE Calculator</h2> |
| 64 | + |
| 65 | + <p className="calculator-summary"> |
| 66 | + <strong>BMR (Basal Metabolic Rate)</strong> is the number of calories your body needs at |
| 67 | + complete rest to maintain essential functions such as breathing, circulation, and |
| 68 | + temperature regulation. |
| 69 | + <br /> |
| 70 | + <br /> |
| 71 | + <strong>TDEE (Total Daily Energy Expenditure)</strong> is the total number of calories your |
| 72 | + body burns in a day, including all physical activities like walking, exercise, and daily |
| 73 | + tasks. |
| 74 | + </p> |
| 75 | + <CalculatorForm formData={formData} onChange={handleChange} /> |
| 76 | + |
| 77 | + <ResultDisplay bmr={bmr} tdee={tdee} /> |
| 78 | + </div> |
| 79 | + ); |
| 80 | +}; |
| 81 | + |
| 82 | +export default BodyCompositionCalculator; |
0 commit comments