If you are looking to build a BMI (Body Mass Index) app in React, you are in the right place. In this article, we will walk you through the process of building a BMI app using React, a popular JavaScript library for building user interfaces.
Step 1. Install Create React App The first step is to create a new React project using Create React App. You can do this by running the following command in your terminal.
npx create-react-app bmi-app
This command will create a new React project with the name 'bmi-app'. Once the project is created, navigate to the project directory by running.
cd bmi-app
In the app.js add the following code.
import React, {useState} from 'react'
import './index.css'
function App() {
// state
const [weight, setWeight] = useState(0)
const [height, setHeight] = useState(0)
const [bmi, setBmi] = useState('')
const [message, setMessage] = useState('')
let calcBmi = (event) => {
//prevent submitting
event.preventDefault()
if (weight === 0 || height === 0) {
alert('Please enter a valid weight and height')
} else {
let bmi = (weight / (height * height)) * 10000
setBmi(bmi.toFixed(1))
// Logic for message
if (bmi < 25) {
setMessage('You are underweight')
} else if (bmi >= 25 && bmi < 30) {
setMessage('You are a healthy weight')
} else {
setMessage('You are overweight')
}
}
}
// show image based on bmi calculation
let imgSrc;
if (bmi < 1) {
imgSrc = null
} else {
if(bmi < 25) {
imgSrc = require('../src/assets/underweight.png')
} else if (bmi >= 25 && bmi < 30) {
imgSrc = require('../src/assets/healthy.png')
} else {
imgSrc = require('../src/assets/overweight.png')
}
}
let reload = () => {
window.location.reload()
}
return (
<div className="app">
<div className='container'>
<h2 className='center'>BMI Calculator</h2>
<form onSubmit={calcBmi}>
<div>
<label>Weight (KG)</label>
<input value={weight} onChange={(e) => setWeight(e.target.value)} />
</div>
<div>
<label>Height (cm)</label>
<input value={height} onChange={(event) => setHeight(event.target.value)} />
</div>
<div>
<button className='btn' type='submit'>Submit</button>
<button className='btn btn-outline' onClick={reload} type='submit'>Reload</button>
</div>
</form>
<div className='center'>
<h3>Your BMI is: {bmi}</h3>
<p>{message}</p>
</div>
<div className='img-container'>
<img src={imgSrc} alt=''></img>
</div>
</div>
</div>
);
}
export default App;
Step 2. Run the App Now that you have created the components, you can run the app by running the following command in the terminal.
npm start
Result
You can get the source code from Github
In conclusion, building a BMI app in React is a simple process. By following these steps, you can create a fully functioning BMI calculator app that can help users track their body mass index. Feel free to customize the app further by adding more features and styling to make it more user-friendly.