Age Calculator Using React-JS
Last Updated :
29 Jul, 2024
In this article, we will create an Age Calculator using ReactJS and Bootstrap. This free age calculator computes age in terms of years, months, weeks, days, hours, minutes, and seconds, given a date of birth. Users can now input their birth year and calculate their current age with just a few clicks. It’s a simple utility designed to determine how many years, months, and days have passed since a person was born.
Preview of Final Output: Let us have a look at how the final output will look like

Prerequisites
Steps to Create and Configure React Native App:
Step 1: Set up React project using the command
npm create vite@latest <<Name of Projext>>
Step 2: Navigate to the project folder using.
cd <<Name_of_project>>
npm install
Step 3: Adding the Bootstrap
npm install [email protected]
Step 4: Include some features as submodules in the npm package.
npm install date-fns --save
Step 5: Create a folder “components” and add four new files in it and name them AgeCalculator.jsx , AgeResult.jsx and import the both file in App.jsx.
Project Structure

The updated dependencies in package.json will look like this:
"dependencies": {
"bootstrap": "^5.3.2",
"date-fns": "^3.3.1",
"react": "^18.2.0",
"react-dom": "^18.2.0"
},
Examples:
- App.jsx:. It utilizes date-fns for date calculations and Bootstrap for styling. The App component manages state, computes age, and renders the UI, including an input for the birth date and a display for the calculated age in years, months, days, weeks, hours, minutes, and seconds.
- AgeCalculator.jsx: It allows users to input a date and calculates age based on that date. The component maintains date state using useState and handles form submission to calculate age via a function provided as a prop. It enforces the calculateAge prop to be a function through PropTypes.
- AgeResult.jsx: This component displays age information in years, months, weeks, days, hours, minutes, and seconds. It takes an age object as a prop, which contains numeric properties for each unit of time. PropTypes are used to ensure that the age prop is an object with specific numeric properties.
HTML
// index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/call.png" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Age-Calculator</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.jsx"></script>
</body>
</html>
JavaScript
// App.jsx
import { useState } from "react";
import { AgeCalculator }
from "./components/AgeCalculator"
import { AgeResult }
from "./components/AgeResult"
import {
differenceInDays,
differenceInHours,
differenceInMinutes,
differenceInMonths,
differenceInSeconds,
differenceInWeeks,
differenceInYears
}
from "date-fns";
import "bootstrap/dist/css/bootstrap.min.css";
function App() {
const [age, setAge] = useState(null);
const calculateAge = (date) => {
const today = new Date();
const dateObject = new Date(date);
const ageYears = differenceInYears(today, dateObject);
const ageMonths = differenceInMonths(today, dateObject);
const ageDays = differenceInDays(today, dateObject);
const ageWeeks = differenceInWeeks(today, dateObject);
const ageHours = differenceInHours(today, dateObject);
const ageMinutes = differenceInMinutes(today, dateObject);
const ageSeconds = differenceInSeconds(today, dateObject);
setAge({
years: ageYears,
months: ageMonths,
days: ageDays,
weeks: ageWeeks,
hours: ageHours,
minutes: ageMinutes,
seconds: ageSeconds,
});
};
return (
<center className="container my-3">
<h1>Age Calculator</h1>
<strong>This free age calculator
computes age in terms of years,
months, weeks, days, hours,
minutes, and seconds,
given a date of birth.
</strong>
<div className="my-3">
<AgeCalculator calculateAge={calculateAge} />
</div>
{age && <AgeResult age={age} />}
</center>
)
}
export default App;
JavaScript
// AgeCalculator.jsx
import { useState } from "react"
import PropTypes from 'prop-types';
export const AgeCalculator = ({ calculateAge }) => {
const [date, setDate] = useState('');
console.log(date);
const handleChangeDate = (val) => {
setDate(val.target.value);
};
const handleSubmit = (val) => {
val.preventDefault();
calculateAge(date);
};
return (
<form onSubmit={handleSubmit}>
<div className="col-auto">
<input value={date} type="date"
className="mb-3"
onChange={handleChangeDate} />
</div>
<div className="col-auto">
<button disabled={!date}
type="submit"
className="btn btn-primary mb-3">
calculate Age
</button>
</div>
</form>
)
};
AgeCalculator.propTypes = {
calculateAge: PropTypes.func.isRequired,
}
JavaScript
// AgeResult.jsx
import PropTypes from 'prop-types';
export const AgeResult = ({ age }) => {
return <>
<h5>You are age is {age.years} Years</h5>
<h5>Or {age.months} Months</h5>
<h5>Or {age.weeks} Weeks</h5>
<h5>Or {age.days} Days</h5>
<h5>Or {age.hours} Hours</h5>
<h5>Or {age.minutes} Minutes</h5>
<h5>Or {age.seconds} Seconds</h5>
</>
};
AgeResult.prototypes = {
age: PropTypes.shape({
years: PropTypes.number.isRequired,
months: PropTypes.number.isRequired,
weeks: PropTypes.number.isRequired,
days: PropTypes.number.isRequired,
hours: PropTypes.number.isRequired,
minutes: PropTypes.number.isRequired,
seconds: PropTypes.number.isRequired,
}),
};
Steps to run the application:
Step 1: Type the following command in terminal
npm run dev
Step 2: Open web-browser and type the following URL.
http://localhost:5173/
Output:
Similar Reads
BMI Calculator Using React In this article, we will create a BMI Calculator application using the ReactJS framework. A BMI calculator determines the relationship between a person's height and weight. It provides a numerical value that categorizes the individual as underweight, normal weight, overweight, or obese.Output Previe
3 min read
GPA Calculator using React GPA Calculator is an application that provides a user interface for calculating and displaying a student's GPA(Grade Point Average). Using functional components and state management, this program enables users to input course information, including course name, credit hours and earned grades and add
5 min read
Tip Calculator using React In this article, we will create a Tip Calculator using ReactJS. This project basically implements functional components and manages the state accordingly using the useState and useEffect hook of ReactJS. The user enters the Bill Amount, Tip Percentage and the number of persons then the output will r
5 min read
ReactJS Calculator App (Styling) Now that we have added functionality to our Calculator app and successfully created a fully functional calculator application using React. But that does not look good despite being fully functional. This is because of the lack of CSS in the code. Let's add CSS to our app to make it look more attract
3 min read
Mortgage Calculator using React In this article, we will create a Mortgage Calculator using React, allowing users to estimate their monthly mortgage payments based on the loan amount, annual rate of interest, and loan term in years. The application provides instant feedback, displaying the calculated monthly payment, total payable
4 min read