BMI Calculator Using React
Last Updated :
24 Jul, 2024
In this article, we will create a BMI Calculator application using the ReactJS framework. A BMI calculator determines the relationship between a person's height and weight. It provides a numerical value that categorizes the individual as underweight, normal weight, overweight, or obese.
Output Preview: Let us have a look at how the final output will look like.
Technologies Used/Pre-requisites:
Approach:
- Create a new React app using npx create-react-app bmi-calculator.
- Create a new file named BmiCalculator.js in the src directory.
- Use a functional component for the BMI calculator.
- We will Use React’s useState to handle input values (height, weight), the calculated BMI, and the BMI category.
- Convert height from centimeters to meters and apply the BMI formula: BMI = weight / (height * height).
- Set the BMI state with the calculated value.
- Determine BMI categories (e.g., Underweight, Normal weight, Overweight, Obesity) based on the calculated BMI.
- Display the BMI result and category.
Steps to create the application:
Step 1: Set up React project using the below command in VSCode IDE.
npx create-react-app <<name of project>>
Step 2: Navigate to the newly created project folder by executing the below command.
cd <<Name_of_project>>
Step 3: Insert the below code in the App.js and styles/App.css files mentioned in the above directory structure.
Project Structure:
The dependencies in package.json will look like this:
"dependencies": {
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
Example: Write following code in respective files(The name of the files is mentioned in the first line of each code block.
CSS
/* BmiCalculator.css */
.container {
max-width: 500px;
margin: 0 auto;
padding: 20px;
background-color: #f9f9f9;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
text-align: center;
}
h1 {
color: #333;
}
.input-group {
margin: 10px 0;
}
.input-group label {
font-size: 16px;
color: #555;
display: block;
margin-bottom: 5px;
}
.input-group input {
padding: 10px;
border: 1px solid #ccc;
border-radius: 5px;
font-size: 16px;
width: calc(100% - 22px);
box-sizing: border-box;
}
button {
padding: 10px 20px;
background-color: #007bff;
color: white;
border: none;
border-radius: 5px;
font-size: 16px;
cursor: pointer;
margin-top: 10px;
}
button:hover {
background-color: #0056b3;
}
.result {
margin-top: 20px;
color: #333;
}
JavaScript
// App.js
import React from 'react';
import BmiCalculator from './BmiCalculator';
import './App.css';
function App() {
return (
<div className="App">
<BmiCalculator />
</div>
);
}
export default App;
JavaScript
// BmiCalculator.js
import React, { useState } from 'react';
import './BmiCalculator.css';
const BmiCalculator = () => {
const [weight, setWeight] = useState('');
const [height, setHeight] = useState('');
const [bmi, setBmi] = useState(null);
const [status, setStatus] = useState('');
const calculateBMI = () => {
if (!weight || !height) {
alert('Please enter both weight and height!');
return;
}
const heightInMeters = parseFloat(height) / 100;
const bmiValue = (parseFloat(weight) / (heightInMeters * heightInMeters)).toFixed(2);
setBmi(bmiValue);
let bmiStatus = '';
if (bmiValue < 18.5) {
bmiStatus = 'Underweight';
} else if (bmiValue < 24.9) {
bmiStatus = 'Normal weight';
} else if (bmiValue < 29.9) {
bmiStatus = 'Overweight';
} else {
bmiStatus = 'Obesity';
}
setStatus(bmiStatus);
};
return (
<div className='container'>
<h1>BMI Calculator</h1>
<div className='input-group'>
<label>
Weight (kg):
<input
type="number"
value={weight}
onChange={(e) => setWeight(e.target.value)}
placeholder='Enter your weight'
/>
</label>
</div>
<div className='input-group'>
<label>
Height (cm):
<input
type="number"
value={height}
onChange={(e) => setHeight(e.target.value)}
placeholder='Enter your height'
/>
</label>
</div>
<button onClick={calculateBMI}>Calculate</button>
{bmi && (
<div className='result'>
<h3>Your BMI: {bmi}</h3>
<h3>Status: {status}</h3>
</div>
)}
</div>
);
};
export default BmiCalculator;
Steps to run the application:
1. Type the following command in the terminal from your VS Code IDE.
npm start
2. Open the web browser and type the following URL in the address bar, to see the live application.
http://localhost:3000/
Output:
Similar Reads
BMI Calculator Using React In this article, we will create a BMI Calculator application using the ReactJS framework. A BMI calculator determines the relationship between a person's height and weight. It provides a numerical value that categorizes the individual as underweight, normal weight, overweight, or obese.Output Previe
3 min read
Create Rock Paper Scissor Game using ReactJS In this article, we will create Rock, Paper, Scissors game using ReactJS. This project basically implements class components and manages the state accordingly. The player uses a particular option from Rock, Paper, or Scissors and then Computer chooses an option randomly. The logic of scoring and win
6 min read
Create a Form using React JS Creating a From in React includes the use of JSX elements to build interactive interfaces for user inputs. We will be using HTML elements to create different input fields and functional component with useState to manage states and handle inputs. Prerequisites:Functional ComponentsJavaScript ES6JSXPr
5 min read
Create a Random Joke using React app through API In this tutorial, we'll make a website that fetches data (joke) from an external API and displays it on the screen. We'll be using React completely to base this website. Each time we reload the page and click the button, a new joke fetched and rendered on the screen by React. As we are using React f
3 min read
Nutrition Meter - Calories Tracker App using React GeeksforGeeks Nutrition Meter application allows users to input the name of a food item or dish they have consumed, along with details on proteins, calories, fat, carbs, etc. Users can then keep track of their calorie intake and receive a warning message if their calorie limit is exceeded. The logic
9 min read
Currency converter app using ReactJS In this article, we will be building a very simple currency converter app with the help of an API. Our app contains three sections, one for taking the user input and storing it inside a state variable, a menu where users can change the units of conversion, and finally, a display section where we dis
4 min read
Lap Memory Stopwatch using React Stopwatch is an application which helps to track time in hours, minutes, seconds, and milliseconds. This application implements all the basic operations of a stopwatch such as start, pause and reset button. It has an additional feature using which we can keep a record of laps which is useful when we
5 min read
Typing Speed Tester using React In this article, we will create a Typing Speed Tester that provides a random paragraph for the user to type as accurately and quickly as possible within a fixed time limit of one minute. This application also displays the time remaining, counts mistakes calculates the words per minute and characters
9 min read
Number Format Converter using React In this article, we will create Number Format Converter, that provides various features for users like to conversion between decimal, binary, octal and hexadecimal representations. Using functional components and state management, this program enables users to input a number and perform a range of c
7 min read
Create a Password Validator using ReactJS Password must be strong so that hackers can not hack them easily. The following example shows how to check the password strength of the user input password in ReactJS. We will use the validator module to achieve this functionality. We will call the isStrongPassword function and pass the conditions a
2 min read