Open In App

Age Calculator Using React-JS

Last Updated : 29 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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

calculator

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

callSh

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:


Next Article

Similar Reads