Home > Web Front-end > JS Tutorial > body text

Building a BMI Calculator with React

PHPz
Release: 2024-09-03 22:39:32
Original
252 people have browsed it

Building a BMI Calculator with React

Building a BMI Calculator with React

Introduction

Body Mass Index (BMI) is a widely used metric to determine if a person has a healthy body weight for a given height. In this blog, we'll walk through the creation of a simple yet functional BMI Calculator using React. This project allows users to input their weight and height to calculate their BMI and provides a classification based on the result.

Project Overview

The BMI Calculator is a responsive web application built with React. It takes the user's weight (in kilograms) and height (in centimeters) as inputs and calculates the BMI. The app then displays the calculated BMI along with a corresponding weight classification such as Underweight, Normal weight, Overweight, or Obesity.

Features

  • User-Friendly Interface: A simple and clean UI that is easy to navigate.
  • Real-Time Calculation: Users can calculate their BMI instantly by entering their weight and height.
  • Responsive Design: The calculator is responsive and works well on different screen sizes.
  • Weight Classification: Based on the calculated BMI, users are informed about their weight status.

Technologies Used

  • React: The core library for building the user interface.
  • JavaScript: For handling the logic of BMI calculation.
  • CSS: To style the application and ensure a responsive design.

Project Structure

Here's a brief overview of the project's structure:

src/
│
├── assets/
│   └── images/
│       └── BMI Logo.png
├── components/
│   └── BmiCalculator.jsx
├── App.jsx
├── App.css
└── index.css
Copy after login

Code Explanation

1. BmiCalculator Component

This component is the heart of the application. It handles user inputs, performs the BMI calculation, and displays the result.

import { useState } from "react";
import logoImg from "../assets/images/BMI Logo.png";

const BmiCalculator = () => {
  const [weight, setWeight] = useState("");
  const [height, setHeight] = useState("");
  const [bmi, setBMI] = useState("");
  const [result, setResult] = useState("");

  function calculateBMI(weight, height) {
    const heightM = height / 100;
    const bmiResult = weight / (heightM * heightM);
    setBMI(bmiResult.toFixed(2)); // Round to 2 decimal places
    if (bmiResult < 18.5) {
      setResult("Underweight");
    } else if (bmiResult < 24.9) {
      setResult("Normal weight");
    } else if (bmiResult < 29.9) {
      setResult("Overweight");
    } else {
      setResult("Obesity");
    }
  }

  const handleCalculateBMI = () => {
    if (weight && height) {
      calculateBMI(weight, height);
    }
  };

  return (
    <div className="bmi-container">
      <div className="logo">
        <img src={logoImg} alt="BMI Logo" />
      </div>
      <div className="input-box">
        <div className="weight-input">
          <h4>Weight (kg)</h4>
          <input
            type="number"
            value={weight}
            onChange={(e) => setWeight(e.target.value)}
          />
        </div>
        <div className="height-input">
          <h4>Height (cm)</h4>
          <input
            type="number"
            value={height}
            onChange={(e) => setHeight(e.target.value)}
          />
        </div>
      </div>
      <button onClick={handleCalculateBMI} className="btn">
        <h2>Calculate BMI</h2>
      </button>
      <div className="output-box">
        <p>Your BMI : <b>{bmi}</b></p>
        <p>Result : <b>{result}</b></p>
      </div>
    </div>
  );
};

export default BmiCalculator;
Copy after login

2. App Component

The App component serves as the main container, wrapping the BmiCalculator component and adding a header and footer.

import BmiCalculator from "./components/BmiCalculator";
import "./App.css";

const App = () => {
  return (
    <div className="app">
      <div className="header">
        <h1>BMI Calculator</h1>
      </div>
      <BmiCalculator />
      <div className="footer">
        <p>Made with ❤️ by Abhishek Gurjar</p>
      </div>
    </div>
  );
};

export default App;
Copy after login

3. Styling the App (App.css)

The CSS ensures that the app is visually appealing and responsive.

* {
  box-sizing: border-box;
}

body {
  margin: 0;
  padding: 0;
  font-family: sans-serif;
  background-color: #008f7d;
  color: white;
}

.app {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  margin-top: 30px;
}

.header {
  text-align: center;
  font-size: 18px;
}

.bmi-container {
  margin: 40px;
  width: 500px;
  height: 430px;
  background-color: white;
  color: black;
  border-radius: 15px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
}

.logo img {
  width: 50px;
  height: 50px;
  margin: 15px;
}

.input-box {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.input-box h4 {
  color: gray;
}

.weight-input,
.height-input {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 25px;
}

.weight-input input,
.height-input input {
  height: 27px;
  width: 180px;
  font-weight: 400;
  font-size: 14px;
  border-radius: 7px;
}

.btn {
  margin: 15px;
  width: 65%;
  height: 10%;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #087fff;
  color: white;
  border: 0.5px solid black;
  border-radius: 7px;
}

.btn:hover {
  background-color: #2570c1;
}

.output-box {
  margin-top: 20px;
  width: 65%;
  height: 15%;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: center;
  background-color: #e2e2e2;
  color: black;
  border-radius: 7px;
  border: 1px solid black;
}

.output-box p {
  margin-left: 20px;
  line-height: 0;
}

.footer {
  text-align: center;
  font-size: 14px;
}
Copy after login

Installation and Usage

To run the BMI Calculator on your local machine, follow these steps:

  1. Clone the Repository:
   git clone https://github.com/abhishekgurjar-in/Bmi_Calculator.git
Copy after login
  1. Install Dependencies: Navigate to the project directory and run:
   npm install
Copy after login
  1. Start the Application: Launch the app by running:
   npm start
Copy after login

The application should open in your default web browser at http://localhost:3000.

Live Demo

Check out the live demo of the BMI Calculator here.

Conclusion

In this project, we built a simple yet effective BMI Calculator using React. This project demonstrates the use of React state management, conditional rendering, and basic styling to create a user-friendly interface. Whether you're just starting with React or looking to practice your skills, this project is a great way to get hands-on experience.

Credits

  • Logo: The BMI logo used in this project is sourced from Unsplash.
  • Inspiration: This project was inspired by various BMI calculators available online.

Author

Abhishek Gurjar is a passionate web developer with a focus on building intuitive and responsive web applications. Follow his journey and explore more projects on GitHub.

The above is the detailed content of Building a BMI Calculator with React. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!