Overview
In this exercise, you will be building a simple Body Mass Index (BMI) calculator app using React. The app will take a user’s weight and height inputs and calculate their BMI using the formula (weight in kilograms / (height in meters)^2). The app will display the calculated BMI along with a message indicating the user’s weight status based on the calculated BMI value.
Instructions
- Build a form component that takes user input for weight (in kilograms) and height (in meters).
- Use state to store the user input values in the form component.
- Create a separate component for calculating the user’s BMI based on the input values. The component should take in the weight and height values as props and calculate the BMI using the formula mentioned in the overview.
- Use conditional rendering to display the calculated BMI value and a message indicating the user’s weight status (e.g. “Underweight”, “Normal weight”, “Overweight”, “Obese”).
- Add event handling to the form component to trigger the BMI calculation and display the results when the user submits the form.
Bonus Requirements
- Allow the user to switch between metric and imperial units for weight and height.
- Add validation to the form to ensure that the user input values are valid numbers within a certain range.
Before you dive into the final output, I want to encourage you to take some time to work through the exercise yourself. I believe that active learning is the most effective way to learn and grow as a developer.
So, grab a pen and paper, fire up your code editor, and get ready to dive into the React BMI Calculator exercise. Once you have completed the exercise, feel free to return to this blog post to compare your solution to mine.
Output for the BMI Calculator exercise
import React, { useState } from 'react';
function BMIForm(props) {
const [weight, setWeight] = useState('');
const [height, setHeight] = useState('');
const handleSubmit = (event) => {
event.preventDefault();
props.onSubmit({ weight, height });
};
return (
<form onSubmit={handleSubmit}>
<label>
Weight (in kg):
<input
type="number"
value={weight}
onChange={(event) => setWeight(event.target.value)}
/>
</label>
<label>
Height (in meters):
<input
type="number"
step="0.01"
value={height}
onChange={(event) => setHeight(event.target.value)}
/>
</label>
<button type="submit">Calculate BMI</button>
</form>
);
}
function BMICalculator(props) {
const { weight, height, units } = props;
const bmi = weight / (height * height);
return (
<div>
<p>Your BMI is: {bmi.toFixed(2)}</p>
<p>Your weight status is: {getWeightStatus(bmi)}</p>
{units === 'metric' ? (
<p>
Note: This calculator uses the metric system. To use the imperial
system, enter your weight in pounds and your height in inches.
</p>
) : (
<p>
Note: This calculator uses the imperial system. To use the metric
system, enter your weight in kilograms and your height in meters.
</p>
)}
</div>
);
}
function getWeightStatus(bmi) {
if (bmi < 18.5) {
return 'Underweight';
} else if (bmi >= 18.5 && bmi <= 24.9) {
return 'Normal weight';
} else if (bmi >= 25 && bmi <= 29.9) {
return 'Overweight';
} else {
return 'Obese';
}
}
function App() {
const [bmiResult, setBmiResult] = useState(null);
const [units, setUnits] = useState('metric');
const handleFormSubmit = ({ weight, height }) => {
setBmiResult({ weight, height });
};
const handleUnitChange = (event) => {
setUnits(event.target.value);
};
return (
<div>
<h1>BMI Calculator</h1>
<p>
Select your preferred units:
<select value={units} onChange={handleUnitChange}>
<option value="metric">Metric</option>
<option value="imperial">Imperial</option>
</select>
</p>
<BMIForm onSubmit={handleFormSubmit} />
{bmiResult && (
<BMICalculator
weight={bmiResult.weight}
height={bmiResult.height}
units={units}
/>
)}
</div>
);
}
export default App;
Applications where the BMI Calculator can be used
You can use the BMI Calculator app in a variety of contexts where calculating body mass index is necessary. For example, you can use it in:
- Fitness and health-related websites or apps that help users track their BMI over time.
- Nutrition websites or apps that offer personalized diet and exercise plans based on a user’s BMI.
- Medical websites or apps that provide information on obesity and related health conditions.
- Corporate wellness programs encourage employees to maintain a healthy lifestyle and offer tools for tracking fitness goals.
- Educational websites or apps that teach about health and wellness, including how to calculate BMI and interpret the results.
Overall, anyone can use the Simple BMI Calculator app wherever they need to calculate their body mass index and promote healthy habits.
Thanks for taking this JavaScript exercise!
I hope you found this exercise both helpful and enjoyable. Additionally, I trust that it has deepened your understanding of React development. Therefore, keep practising and experimenting with React, and you’ll be well on your way to becoming a skilled React developer!
Boost your React skills with 25 React JavaScript Practice Exercises with Solutions hands-on challenges to master components, hooks, and more!