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 Previ
3 min read
Aspect Ratio Calculator using React
In this React project, we'll build an interactive Aspect Ratio Calculator where users can upload images to visualize aspect ratios and adjust width and height values for live previews. Preview of final output: Let us have a look at how the final output will look like. PrerequisitesReactCSSJSXFunctio
4 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
6 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
Create a Form using React JS
Creating a From in React includes the use of JSX elements to build interactive interfaces for user inputs. We will be using HTML elements to create different input fields and functional component with useState to manage states and handle inputs. Prerequisites:Functional ComponentsJavaScript ES6JSXPr
5 min read
Build a Calculator using React Native
React Native is a well-known technology for developing mobile apps that can run across many platforms. It enables the creation of native mobile apps for iOS and Android from a single codebase. React Native makes it simple to construct vibrant, engaging, and high-performing mobile apps. In this tutor
6 min read
Create a Calculator App Using Next JS
Creating a Calculator app is one of the basic projects that clears the core concept of a technology. In this tutorial, we'll walk you through the process of building a calculator app using Next.js. Output Preview: Let us have a look at how the final output will look like. Prerequisites:NPM & Nod
3 min read
Calculator App Using TypeScript
A calculator app is a perfect project for practising TypeScript along with HTML and CSS. This app will have basic functionalities like addition, subtraction, multiplication, and division. It provides a clean and interactive interface for the user while using TypeScript to handle logic safely and eff
6 min read
Build a Loan Calculator using Next.js
The Loan Calculator allows users to determine loan amount, interest rate, and tenure, calculate monthly mortgage payments, total loan payments over tenure, and total interest payable. In this article, we will walk you through the process of building a Loan Calculator using Next.js. Let's take a look
4 min read