Skip to content
Tutorials Center
My learning

Topics

Lesson 121 of 132 ยท Projects

Project: Small Utility Apps (BMI, Word Counter, Card Validator)

Build four small React utilities - a BMI calculator, a word and letter counter, a credit card validator with input masking and a scroll-aware navbar - and learn derived state.

Many classic React exercises are tiny tools: a calculator for one formula, a counter for a text box, a validator for one kind of input. They look too small to teach anything, but they all train the same habit that matters most in React: store the minimum, compute the rest. A BMI calculator does not need a "bmi" state variable; it needs height and weight, and the result is a calculation during render.

In this project you will build four of these tools. Each is one component, each one can be tested by reading its pure helper function, and each shows a different input trick: numeric fields, derived statistics, formatting while typing, and reacting to scrolling. If you need a refresher first, read useState, forms and inputs and useEffect.

Project 1: BMI calculator

Body mass index is weight in kilograms divided by height in meters squared. The user types two numbers; you show the index and a category.

Three decisions make this robust:

  1. Keep the raw text in state. An input's value is always a string. If you store Number(value) immediately, typing 1. turns into 1 and the user can never type a decimal point. Store the string, convert when you calculate.
  2. Validate in the calculation, not in the handler. The helper returns null when either number is missing or not positive; the component then shows a hint instead of NaN or Infinity.
  3. Derive the result. No effect, no extra state.
BMI calculator

The console shows { value: 22.9, category: 'Healthy range' } for 70 kg and 175 cm, and null for the incomplete input. Notice type="number" with step="any": without step, the browser only accepts whole numbers as valid and marks decimals as errors. inputMode="decimal" opens a numeric keypad with a decimal point on phones.

Allowing only floating-point input. type="number" is the simplest way to accept decimals. If you want a plain text field that rejects letters as the user types, validate in onChange and refuse the update: if (/^\d*\.?\d*$/.test(next)) setValue(next);. The regular expression allows digits with at most one dot, including the in-progress states "" and "3.".

Project 2: Word and letter counter

A counter needs one piece of state: the text. Every statistic is a calculation from it, so they can never disagree with the text box.

The details are in the definitions. Splitting on a single space gives wrong answers for double spaces and line breaks, so split on runs of whitespace and drop empty parts. Characters are counted twice, with and without spaces. Reading time is words divided by an average speed (about 200 words per minute for silent reading).

Word and letter counter

The sample text gives 8 words and 2 sentences. [...text].length counts characters by code point, so an emoji counts as one (plain text.length would count it as two). The \p{L} pattern with the u flag matches letters in any alphabet, not only A to Z. The three buttons show the other half of the lesson: buttons only change text, and the numbers follow without any extra code.

Project 3: Credit card number validator

Card numbers carry a built-in check digit called the Luhn algorithm. Starting from the rightmost digit, double every second digit, subtract 9 from any result above 9, add everything up, and the total must be divisible by 10. It catches most single-digit typos and transpositions. It does not prove that a card exists or has money, and you should never send real card numbers to a test page.

This project adds a second skill: formatting while typing. The user types digits, and you show them in groups of four. Store only the digits, then format for display; that way the stored value stays clean and the display rule lives in one function.

Card number validator (use test numbers only)

The console prints true false: the well-known test number passes, and changing its last digit breaks the checksum. The onChange handler removes everything that is not a digit and limits the length, so pasting 4242-4242-4242-4242 also works. A password validator uses the same structure: keep the password in state and compute a list of rules (length, digit, symbol) that each turn green or red.

A checksum is a convenience for the user, not security. Real payment forms use a payment provider's hosted fields so card numbers never touch your own code.

Project 4: A navbar that changes while you scroll

The last tool reacts to the page instead of to typing. A header starts transparent and turns solid after the user scrolls down. This needs an effect: you subscribe to an event outside React, and you must unsubscribe in the cleanup (see effect cleanup).

Two details matter. First, set only a boolean (scrolled): React skips the render when the value does not change, so most scroll events cost almost nothing. Second, register the listener as passive so the browser never waits for your code before scrolling.

Scroll-aware navbar and a toggle switch

The panel scrolls instead of the whole page because the preview iframe is small; in a real app you would listen on window. The toggle is a real checkbox with role="switch", visually hidden but still focusable, so keyboard and screen reader users can use it. The colored track is just decoration, which is why it carries aria-hidden. The same Toggle can be reused anywhere because it knows nothing about what it controls.

Where to go from here

  • Put calculateBmi, analyze and passesLuhn in their own files and test them with Vitest; pure functions need no React in the test at all.
  • Add unit switching (pounds and inches) to the BMI tool and decide which state is the source of truth. Keep one unit internally and convert for display.
  • Turn the word counter into a controlled-and-uncontrolled hybrid by saving the text with a debounced effect, as described in async patterns.
  • Replace the hand-made toggle with the same component in a settings form.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the BMI tool keep the input values as strings in state?

    An input's value is text. Storing the raw text lets the user type a decimal point or clear the field; you convert to a number only when calculating.
  2. 2. The word counter shows words, letters and reading time. How many state variables does it need?

    Everything can be computed from the text. Storing the statistics too would create extra state that can fall out of sync.
  3. 3. In the card validator, why is only the digit string stored, not the formatted text?

    Store the data, format for display. The checksum and brand detection work on plain digits, and the grouping is applied only in the input's value prop.
  4. 4. What is the purpose of the cleanup function returned by the scroll effect?

    An effect that subscribes to something outside React must unsubscribe. Otherwise the old listener keeps running and calls setState on a component that is gone.

Summary

  • Store the minimum state (raw input text) and compute results, categories and statistics during render.
  • Keep numeric input as a string until you calculate; use type="number", step="any" and inputMode="decimal" for decimals, or filter text with a regular expression.
  • Count words by splitting on whitespace runs, and count characters by code point so emoji and non-Latin letters are correct.
  • Format while typing by storing clean digits and formatting only in the value prop. The Luhn checksum catches typos, not fraud.
  • For scroll-driven styling, subscribe in an effect, clean up, use a passive listener and set only a boolean.
  • A custom switch should be a real checkbox with role="switch", not a styled div.

Next: Project: Password Generator and QR Code Maker