React is an easy to use JavaScript framework that lets us create front end apps.
In this article, we’ll look at how to create a BMI calculator app with React and JavaScript.
Create the Project
We can create the React project with Create React App.
To install it, we run:
npx create-react-app bmi-calculator
with NPM to create our React project.
Create the BMI Calculator App
To create the BMI calculator app, we write:
import React, { useState } from "react";
export default function App() {
const [height, setHeight] = useState(0);
const [mass, setMass] = useState(0);
const [bmi, setBmi] = useState(0);
const calculate = (e) => {
e.preventDefault();
const formValid = +height > 0 && +mass > 0;
if (!formValid) {
return;
}
const bmi = +mass / (+height) ** 2;
setBmi(bmi);
};
return (
<div className="App">
<form onSubmit={calculate}>
<div>
<label>height in meters</label>
<input value={height} onChange={(e) => setHeight(e.target.value)} />
</div>
<div>
<label>mass in kg</label>
<input value={mass} onChange={(e) => setMass(e.target.value)} />
</div>
<button type="submit">calculate</button>
</form>
<p>bmi: {bmi}</p>
</div>
);
}
First, we defined the height
, mass
and bmi
states with the useState
hook.
Then, we have the calculate
function to calculate the bmi
from the height
and mass
.
In it, we call e.preventDefault()
to do client-side form submission.
Then we check if height
and mass
are valid values.
If they are, then we calculate the bmi
and call setBmi
to set the BMI value.
Then we return a form with the onSubmit
prop set to calculate
.
It’s run when we click on the calculate button.
Also, we have 2 inputs that take the inputted value and set them as the value height
and mass
respectively.
e.target.value
has the inputted value.
Below the form, we display the bmi
.
Conclusion
We can create a BMI calculator easily with React and JavaScript.