In this article, we will create a BMI (Body Mass Index) calculator using React Native. A BMI calculator serves as a valuable and straightforward tool for estimating body fat by considering height and weight measurements.A BMI Calculator App built with React Native allows users to input their age, height, weight, and gender. It computes their Body Mass Index (BMI) and provides a health category based on the result.
Prerequisites
- Introduction to React Native
- React Native Components
- React Hooks
- Node.js and NPM
Steps to Create React Native Application
Step 1: Create a React Native Application
Create a new React Native project for BMICalculatorApp
npx create-expo-app BMICalculatorApp
Step 2: Change the directory to the project folder
cd BMICalculatorApp
Project Structure
Package.json
{
"dependencies": {
"react-native-paper": "4.9.2",
"@expo/vector-icons": "^13.0.0"
}
}
Approach
- The validateForm function holds great significance in validating user input. Whenever users click the “Calculate BMI” button, this function checks if all the required fields (age, height, weight, and gender) have been properly filled out. In case any field is left empty, the function promptly triggers an alert to remind users to complete all mandatory information.
- The countBmi function has the responsibility of calculating BMI. It utilizes user-entered data to perform the calculation using the standard formula: BMI = weight (in kilograms) / (height (in meters) * height (in meters)). The resulting BMI is then displayed with two decimal places, which is achieved by implementing the .toFixed(2) method.
- Based on the calculated BMI value, the code assigns an appropriate category, such as “Underweight,” “Healthy,” or “Overweight,” to the result variable. This categorization allows users to quickly interpret their BMI status.
Example: In this example we are using the above-explained apporach.
- App.js
Javascript
// App.js import React, { useState } from 'react' ; import { View, Text, TextInput, TouchableOpacity, StyleSheet } from 'react-native' ; const App = () => { const [age, setAge] = useState( '' ); const [height, setHeight] = useState( '' ); const [weight, setWeight] = useState( '' ); const [gender, setGender] = useState( '' ); const [bmiResult, setBmiResult] = useState( null ); const validateForm = () => { if (!age || !height || !weight || !gender) { alert( 'All fields are required!' ); } else { countBmi(); } }; const countBmi = () => { const bmi = (parseFloat(weight) / ((parseFloat(height) / 100) ** 2)).toFixed(2); let result = '' ; if (bmi < 18.5) { result = 'Underweight' ; } else if (bmi >= 18.5 && bmi <= 24.9) { result = 'Healthy' ; } else if (bmi >= 25 && bmi <= 29.9) { result = 'Overweight' ; } else if (bmi >= 30 && bmi <= 34.9) { result = 'Obese' ; } else if (bmi >= 35) { result = 'Extremely obese' ; } // Set the BMI result setBmiResult({ bmi, result }); // Reset the form setAge( '' ); setHeight( '' ); setWeight( '' ); setGender( '' ); }; return ( <View style={styles.container}> <Text style={styles.header}> BMI Calculator </Text> <View style={styles.form}> <View style={styles.inputRow}> <Text style={styles.label}> Age </Text> <TextInput style={styles.textInput} placeholder= "Enter your age" onChangeText={setAge} value={age} keyboardType= "numeric" /> </View> <View style={styles.inputRow}> <Text style={styles.label}> Height (cm) </Text> <TextInput style={styles.textInput} placeholder= "Enter your height" onChangeText={setHeight} value={height} keyboardType= "numeric" /> </View> <View style={styles.inputRow}> <Text style={styles.label}> Weight (kg) </Text> <TextInput style={styles.textInput} placeholder= "Enter your weight" onChangeText={setWeight} value={weight} keyboardType= "numeric" /> </View> <View style={styles.genderRow}> <TouchableOpacity style={[ styles.genderButton, gender === 'male' && styles.selectedGender, ]} onPress={() => setGender( 'male' )} > <Text style={styles.genderText}> Male </Text> </TouchableOpacity> <TouchableOpacity style={[ styles.genderButton, gender === 'female' && styles.selectedGender, ]} onPress={() => setGender( 'female' )} > <Text style={styles.genderText}>Female</Text> </TouchableOpacity> </View> <TouchableOpacity style={styles.submitButton} onPress={validateForm} > <Text style={styles.submitButtonText}> Calculate BMI </Text> </TouchableOpacity> {bmiResult && ( <View style={styles.resultContainer}> <Text style={styles.resultLabel}> BMI: </Text> <Text style={styles.resultText}> {bmiResult.bmi} </Text> <Text style={styles.resultLabel}> Result: </Text> <Text style={styles.resultText}> {bmiResult.result} </Text> </View> )} </View> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#eef2f3' , alignItems: 'center' , justifyContent: 'center' , }, header: { fontSize: 28, fontWeight: 'bold' , color: '#289df6' , marginBottom: 20, }, form: { backgroundColor: '#fff' , borderRadius: 20, padding: 20, width: '90%' , elevation: 5, }, inputRow: { flexDirection: 'row' , alignItems: 'center' , justifyContent: 'space-between' , marginBottom: 20, }, label: { flex: 1, fontSize: 18, fontWeight: 'bold' , marginRight: 10, }, textInput: { flex: 2, height: 40, borderWidth: 1, borderColor: '#ddd' , borderRadius: 10, paddingLeft: 10, fontSize: 16, }, genderRow: { flexDirection: 'row' , justifyContent: 'space-between' , marginBottom: 20, }, genderButton: { flex: 1, height: 40, borderRadius: 10, justifyContent: 'center' , alignItems: 'center' , backgroundColor: '#dbeffe' , padding: 10, margin: 10, }, selectedGender: { backgroundColor: '#289df6' , }, genderText: { fontSize: 16, fontWeight: 'bold' , color: '#333' , }, submitButton: { backgroundColor: '#289df6' , borderRadius: 10, height: 50, justifyContent: 'center' , alignItems: 'center' , }, submitButtonText: { fontSize: 18, fontWeight: 'bold' , color: '#fff' , }, resultContainer: { marginTop: 20, }, resultLabel: { fontSize: 18, fontWeight: 'bold' , marginBottom: 5, }, resultText: { fontSize: 16, }, }); export default App; |
Step 3: To run react native application use the following command:
npx expo start
To run on Android:
npx react-native run-android
To run on iOS:
npx react-native run-ios
Output: