An age calculator in React combines a date input, React state, calendar-aware birthday logic, validation, and a result component. React handles the interface and state updates; the actual age calculation is ordinary JavaScript date logic.
Quick answer: age calculator in React

A practical React age calculator needs three pieces: a DOB stored in state, a function that calculates completed years from that DOB, and JSX that displays the result. The native HTML <input type="date"> is useful because browsers normalize its value to YYYY-MM-DD.
import { useState } from "react";
function calculateAge(dob) {
const birth = new Date(`${dob}T00:00:00`);
const today = new Date();
let age = today.getFullYear() - birth.getFullYear();
const beforeBirthday = today.getMonth() < birth.getMonth() ||
(today.getMonth() === birth.getMonth() && today.getDate() < birth.getDate());
if (beforeBirthday) age--;
return age;
}
export default function AgeCalculator() {
const [dob, setDob] = useState("");
const age = dob ? calculateAge(dob) : null;
return (
<div>
<label>Date of birth
<input type="date" value={dob}
onChange={(event) => setDob(event.target.value)} />
</label>
{age !== null && <p>Age: {age} years</p>}
</div>
);
}React’s official documentation describes components as functions that return markup and explains how state and events update the screen. The calculation itself remains ordinary JavaScript date logic.
How a React age calculator works
- Input: the user selects a date of birth.
- State: React stores the selected DOB with
useState. - Calculation: JavaScript compares the birthday with today’s month and day.
- Rendering: JSX displays the completed age.
- Validation: the component rejects empty, future, or invalid dates before calculation.
React does not provide an age-calculation API. Keeping the calculation in a small function makes the component easier to test and reuse.
Build the date-of-birth input
Use a native date input for a straightforward browser UI:
<label htmlFor="dob">Date of birth</label>
<input id="dob" name="dob" type="date" value={dob}
onChange={(event) => setDob(event.target.value)}
max={new Date().toISOString().slice(0, 10)} />MDN documents that a date input’s value is normalized to yyyy-mm-dd, while its displayed format can vary by browser locale. It also supports min and max constraints.
Calculate completed age correctly
The common mistake is to calculate only currentYear - birthYear. That can produce an age one year too high when the birthday has not occurred yet.
function calculateAge(dob) {
const birth = new Date(`${dob}T00:00:00`);
const today = new Date();
let years = today.getFullYear() - birth.getFullYear();
const birthdayHasNotArrived =
today.getMonth() < birth.getMonth() ||
(today.getMonth() === birth.getMonth() && today.getDate() < birth.getDate());
if (birthdayHasNotArrived) years -= 1;
return years;
}Add validation for empty and future DOBs
Browser constraints are helpful, but application logic should still validate the value before displaying an age.
function getDobError(dob) {
if (!dob) return "Enter a date of birth.";
const birth = new Date(`${dob}T00:00:00`);
const today = new Date();
if (Number.isNaN(birth.getTime())) return "Enter a valid date.";
if (birth > today) return "Date of birth cannot be in the future.";
return "";
}Use React state for the form
const [dob, setDob] = useState("");
const [error, setError] = useState("");
function handleChange(event) {
const value = event.target.value;
setDob(value);
setError(getDobError(value));
}Then connect the handler to the date field and show errors with a clear message:
<input type="date" value={dob} onChange={handleChange} />
{error && <p role="alert">{error}</p>}Create a complete React age calculator component
import { useState } from "react";
function calculateAge(dob) {
const birth = new Date(`${dob}T00:00:00`);
const today = new Date();
let age = today.getFullYear() - birth.getFullYear();
const beforeBirthday =
today.getMonth() < birth.getMonth() ||
(today.getMonth() === birth.getMonth() && today.getDate() < birth.getDate());
if (beforeBirthday) age--;
return age;
}
export default function AgeCalculator() {
const [dob, setDob] = useState("");
const [error, setError] = useState("");
function handleChange(event) {
const value = event.target.value;
setDob(value);
if (!value) {
setError("Enter a date of birth.");
return;
}
const birth = new Date(`${value}T00:00:00`);
if (Number.isNaN(birth.getTime())) {
setError("Enter a valid date.");
return;
}
if (birth > new Date()) {
setError("Date of birth cannot be in the future.");
return;
}
setError("");
}
const age = dob && !error ? calculateAge(dob) : null;
return (
<section>
<h2>Age Calculator</h2>
<label htmlFor="dob">Date of birth</label>
<input id="dob" type="date" value={dob} onChange={handleChange} />
{error && <p role="alert">{error}</p>}
{age !== null && <p>You are {age} years old.</p>}
</section>
);
}Calculate age on a fixed date
For historical reports, eligibility checks, or testing, use an explicit as-of date instead of always using the current date.
function calculateAgeOnDate(dob, asOf) {
const birth = new Date(`${dob}T00:00:00`);
const target = new Date(`${asOf}T00:00:00`);
let age = target.getFullYear() - birth.getFullYear();
const beforeBirthday =
target.getMonth() < birth.getMonth() ||
(target.getMonth() === birth.getMonth() && target.getDate() < birth.getDate());
if (beforeBirthday) age--;
return age;
}
calculateAgeOnDate("2000-12-15", "2026-10-01"); // 25Calculate years, months and days in React
If the UI needs an exact calendar breakdown, calculate it separately from completed years. Calendar arithmetic needs careful boundary testing around month ends and leap days.
function exactAge(dob, asOf = new Date()) {
const birth = new Date(`${dob}T00:00:00`);
const target = new Date(asOf);
let years = target.getFullYear() - birth.getFullYear();
const birthdayThisYear = new Date(target);
birthdayThisYear.setFullYear(birth.getFullYear());
if (birthdayThisYear > target) years--;
const anchor = new Date(birth);
anchor.setFullYear(birth.getFullYear() + years);
let months = 0;
const cursor = new Date(anchor);
while (true) {
const next = new Date(cursor);
next.setMonth(next.getMonth() + 1);
if (next > target) break;
cursor.setTime(next.getTime());
months++;
}
const days = Math.floor((target - cursor) / 86400000);
return { years, months, days };
}Handle February 29 birthdays
A February 29 DOB is an edge case because most years do not contain that calendar date. Document the convention your application uses in non-leap years. For eligibility or legal rules, follow the applicable requirement rather than inventing a convention.
Improve the React age calculator UI
- Use a visible
<label>for the DOB field. - Use
role="alert"for validation errors that need immediate attention. - Keep the result close to the input.
- Do not rely on color alone to communicate errors.
- Keep calculation logic separate from presentation when possible.
Test the age calculator component
Test the calculation independently and test the component’s visible behavior. Boundary cases are more useful than only testing an ordinary birthday.
| Test case | Expected behavior |
|---|---|
| Empty DOB | Show validation message |
| Future DOB | Reject the value |
| Birthday today | Show the new completed age |
| Birthday tomorrow | Age remains one year lower |
| 29 February DOB | Follow the documented leap-day policy |
| Fixed as-of date | Return a reproducible result |
Common React age-calculator mistakes
- Subtracting years only: ignores the birthday.
- Dividing milliseconds by 365 days: does not represent calendar age.
- Trusting browser validation alone: validate in application logic too.
- Mixing local dates and timestamps carelessly: timezone conversions can shift a date.
- Putting all logic in JSX: a separate function is easier to test.
- Ignoring leap-day policy: document expected behavior.
- Forgetting accessibility: labels and clear errors matter.
React age calculator vs plain JavaScript
| Feature | React | Plain JavaScript |
|---|---|---|
| UI updates | State-driven rendering | Manual DOM updates |
| Input state | useState | DOM element values |
| Reusable UI | Components | Functions/modules |
| Age calculation | JavaScript function | JavaScript function |
The age formula itself does not become more accurate because it is inside React. React organizes the interactive interface and state around the calculation.
FAQ: age calculator in React
How do I make an age calculator in React?
Store the DOB in React state, connect it to an <input type="date">, calculate completed years with birthday-aware JavaScript logic, and render the result conditionally.
Does React have a built-in age calculator?
No. React provides the component and state framework; the age calculation is JavaScript date logic.
How do I prevent future dates in a React DOB field?
Set the date input’s max to today’s date and validate the value in React before calculating.
Can React calculate age on a specific date?
Yes. Pass the DOB and an explicit as-of date into a calculation function.
Can I show age in years, months and days?
Yes, but use calendar-aware logic and test month ends, leap years, and February 29 carefully.
Related age-calculator programming guides
For the same DOB problem in other technologies, see our guides for age calculator in JavaScript, age calculator in Python, age calculator in Java, and age calculator in SQL.
Sources and documentation
Bottom line: build the React interface with controlled state, keep age calculation in a testable JavaScript function, validate the DOB, and handle calendar boundaries explicitly.