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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Steady State Response In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
Use Case Diagram - Unified Modeling Language (UML) A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
9 min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read