Implementing BMI Calculator Project

Step-by-Step Implementation of BMI Calculator

Here’s where the real action begins. This module guides you through setting up the project, building the components, wiring up logic, and styling the app, all from scratch.

Set Up the Environment

Let’s begin by setting up our development environment and creating a new React project.

Install Node.js and Create-React-App:

If you haven’t already, install Node.js (which includes npm). Once installed, open a terminal/command prompt. Use Create React App to bootstrap a new project by running:

npx create-react-app bmi-calculator

This will generate a new React project in a folder named bmi-calculator (you can choose a different project name). Create React App sets up the project structure and installs all necessary dependencies.

Navigate and Start the Dev Server: Move into the project directory and start the development server:

cd bmi-calculator

npm start

This will launch the React app in development mode. By default, it should open http://localhost:3000 in your browser, displaying a welcome React page. This confirms our environment is set up correctly.

Create Application Structure (Directory Structure)

After running Create React App, you get a standard React project structure. Here’s a simplified view of the important files and folders we will work with in the bmi-calculator project:

bmi-calculator/

├── package.json              // Project metadata and dependencies

├── public/

│   └── index.html            // HTML template

└── src/

├── index.js              // JS entry point, renders the App

├── App.js                // Main App component

├── App.css               // Global CSS for App component

├── BmiCalculator.js      // BMI Calculator component (we will create this)

└── BmiCalculator.css     // CSS for BMI Calculator component (we will create this)

Let’s briefly understand these files:

  • index.html: The single HTML page of our app (since React apps are SPA). It contains a root <div> where our React app is mounted.
  • index.js: The JavaScript entry point. It uses ReactDOM.render (or createRoot) to render the <App /> component into the HTML page’s root div. You typically won’t edit this much beyond initial setup.
  • App.js: The top-level React component. This was created by default. We’ll modify it to include our BMI Calculator UI. Think of App.js as the parent container for our app content.
  • App.css: Default styling for the App component. We can keep some basic styles or modify them.
  • BmiCalculator.js: This is our custom component where the BMI form and calculation logic will reside. We will create this file inside src/.
  • BmiCalculator.css: A corresponding CSS file for styling the BMI Calculator component. We will create this as well, to keep styles specific to the calculator (like layout, fonts, colors for the form and result text). This CSS will be imported into BmiCalculator.js.

The node_modules directory (not shown above) contains all npm packages (React and others) that were installed. We won’t touch that directly. Now that we know the structure, let’s start implementing the BMI calculator component and integrate it into our app.

Steps to Build the BMI Calculator Application

Now we will proceed with building the application step by step.

Step 1: Create the BMI Calculator Component

In the src folder of the project, create a new file named BmiCalculator.js. This component will handle the UI and logic for the BMI Calculator. Open BmiCalculator.js and add the following code:

// BmiCalculator.js
import React, { useState } from 'react';
import './BmiCalculator.css';  // Import CSS for styling

function BmiCalculator() {
  // State variables for inputs and results
  const [weight, setWeight] = useState('');
  const [height, setHeight] = useState('');
  const [bmi, setBmi] = useState(null);
  const [status, setStatus] = useState('');

  // Event handler to calculate BMI when button is clicked
  const calculateBMI = () => {
    // Simple validation: ensure weight and height are provided
    if (!weight || !height) {
      alert('Please enter both weight and height!');
      return;
    }
    // Calculate BMI = weight (kg) / [height (m)]^2
    const heightInMeters = parseFloat(height) / 100;  // convert cm to m
    const bmiValue = (parseFloat(weight) / (heightInMeters * heightInMeters)).toFixed(2);
    setBmi(bmiValue);

    // Determine BMI category based on standard ranges
    let bmiStatus = '';
    if (bmiValue < 18.5) {
      bmiStatus = 'Underweight';
    } else if (bmiValue < 25) {
      bmiStatus = 'Normal weight';
    } else if (bmiValue < 30) {
      bmiStatus = 'Overweight';
    } else {
      bmiStatus = 'Obese';
    }
    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 weight in kg" 
          />
        </label>
      </div>
      <div className="input-group">
        <label>Height (cm): 
          <input 
            type="number" 
            value={height}
            onChange={(e) => setHeight(e.target.value)}
            placeholder="Enter height in cm" 
          />
        </label>
      </div>
      <button onClick={calculateBMI}>Calculate BMI</button>

      {/* Display the result only when BMI is calculated */}
      {bmi && (
        <div className="result">
          <h3>Your BMI: {bmi}</h3>
          <h3>Status: {status}</h3>
        </div>
      )}
    </div>
  );
}

export default BmiCalculator;

Let’s break down what’s happening in this code:

  • We import useState from React, which is used to create state variables inside our functional component. We also import a CSS file for styling (which we will create next).
  • We define the BmiCalculator component as a function. Inside, we use useState four times to create state for weight, height, bmi, and status.
    • weight and height state will hold the user’s input values. We initialize them to empty strings ('') since initially there is no input.
    • bmi will hold the calculated BMI number (we initialize it as null meaning no result yet).
    • status will hold the text description of the BMI category (also initially empty).

Step 2: Style the BMI Calculator (CSS)

Create a file BmiCalculator.css in the src directory. Here we write some basic CSS to make the form look clean and centered. You can add the following styles:

/* BmiCalculator.css */
.container {
  max-width: 500px;
  margin: 2rem auto;
  padding: 20px;
  background-color: #f0f0f0;
  border-radius: 8px;
  text-align: center;
}

h1 {
  color: #333;
  margin-bottom: 1rem;
}

.input-group {
  margin: 10px 0;
  text-align: left;
}

.input-group label {
  font-size: 16px;
  color: #555;
}

.input-group input {
  display: block;
  width: 100%;
  padding: 8px;
  margin-top: 5px;
  font-size: 15px;
  box-sizing: border-box;
}

button {
  padding: 10px 20px;
  margin-top: 15px;
  font-size: 16px;
  cursor: pointer;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 5px;
}

button:hover {
  background-color: #45a049;
}

.result {
  margin-top: 20px;
  font-weight: bold;
  color: #333;
}

Feel free to tweak the colors or spacing as desired. The goal is just to make the app UI clear and pleasant.

Step 3: Integrate the Component in App.js

Now that we have BmiCalculator component (and its CSS) ready, we need to use it in our main app. Open App.js (which was generated by Create React App) and replace its content with the following:

// App.js
import React from 'react';
import BmiCalculator from './BmiCalculator';

function App() {
  return (
    <div className="App">
      <BmiCalculator />
    </div>
  );
}

export default App;

We import the BmiCalculator component at the top. In the JSX, the App component returns a div containing <BmiCalculator />.

This means when App renders, it will display whatever our BmiCalculator component renders. We keep <div className="App"> as a container.

Step 4: Run and Test the Application

With the code in place, let’s test the app in development. If you still have npm start running, it should auto-reload the changes. If not, start the dev server again with npm start.  You should see the BMI Calculator interface: the title, two input fields, and a Calculate button.

Try entering a weight and height (for example, 70 and 170) and click "Calculate BMI". The app should display the BMI value (for 70kg/170cm it should be around 24.22) and the category ("Normal weight").

At this point, the BMI Calculator functionality is complete! You have a working React application on your localhost. The next steps will involve preparing the app for deployment and putting it online.