Horje
Create an Age Calculator App using React-Native

In this article we are going to implement a Age calculator using React Native. An age calculator app in React Native is a simple application that calculates a person’s age based on their birth date and the current date. 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.

age

Output of the Age calculator

Prerequisites

Steps to Create & Configure React Native App:

Step 1: Create a new React Native project.

npx react-native init TextEditorApp

Step 2: Navigate to the project directory:

cd TextEditorApp

Project Structure:

Screenshot-2566-10-21-at-145325

Approach

Age calculator app in React Native is a simple application that calculates a person’s age based on their birth date and the current date. Therefore, we will take date of birth as input from user and after entering date of birth when user click on calculate age then they will see their age in the format of years, months and days.

Example

JavaScript
import React, { useState } from "react";
import {
    View,Text,TextInput,
    Button,StyleSheet,
} from "react-native";

const AgeCalculator = () => {
    const [birthdate, setBirthdate] =
        useState("");
    const [age, setAge] = useState("");

    const calculateAge = () => {
        const currentDate = new Date();
        const birthdateArray =
            birthdate.split("/");

        if ( birthdateArray.length === 3 ) {
            const day = parseInt(
                birthdateArray[0], 10);
            const month = parseInt(
                birthdateArray[1], 10);
            const year = parseInt(
                birthdateArray[2],10);

            if (!isNaN(day) &&
                !isNaN(month) &&
                !isNaN(year)) {
                const birthDate =
                    new Date(year,month - 1,day); 

                // Calculate the age
                const ageInMilliseconds =
                    currentDate - birthDate;
                const ageInYears =
                    ageInMilliseconds /
                    (1000 * 60 * 60 * 24 * 365.25); 
                const ageYears =
                    Math.floor(ageInYears );
                const ageMonths =
                    Math.floor(
                        (ageInYears - ageYears) * 12);
                const ageDays =
                    Math.floor(
                        (ageInYears - ageYears) *
                        365.25 - ageMonths * 30.44);

                setAge(
`Your age is : ${ageYears} years, ${ageMonths} months, and ${ageDays} days.`);
                return;}}
        setAge(
"Please enter a valid date in the format: dd/mm/yyyy");};

    return (
        <View style={styles.container}>
            <View style={styles.logo}>
                <Text
                    style={
                        styles.logotext}>
                    {" "}
                    GeekforGeeks{" "}
                </Text>
            </View>
            <Text style={styles.header}>
                Age Calculator
            </Text>
            <TextInput
                style={styles.input}
                placeholder="Enter your birthdate (dd/mm/yyyy)"
                onChangeText={(text) =>
                    setBirthdate(text)}/>
            <Button
                title="Calculate Age"
                onPress={calculateAge}/>
            <Text style={styles.result}>
                {age}
            </Text>
        </View>
);};

const styles = StyleSheet.create({
    container: {
        flex: 1,
        alignItems: "center",
        backgroundColor: "#f0f0f0",
    },
    logo: {
        width: 150,
        height: 150,
        backgroundColor: "lightgreen",
        borderRadius: 150,
        marginTop: 50,
    },
    logotext: {
        alignItems: "center",
        justifyContent: "center",
        marginLeft: 25,
        marginTop: 60,
        fontWeight: "bold",
        fontSize: 15,
    },
    header: {
        fontSize: 24,
        marginBottom: 20,
    },
    input: {
        width: 200,
        height: 40,
        borderColor: "gray",
        borderWidth: 1,
        paddingLeft: 10,
        marginBottom: 10,
    },
    result: {
        fontSize: 20,
        marginTop: 20,
    },
});

export default AgeCalculator;

Steps to run your application:

Step 1: Type following command in your terminal.

npx expo start

Step 2: According to your operating system run the following command.

  • To run on Android
npx react-native run-android
  • To run on IOS
npx react-native run-ios

Output




Reffered: https://www.geeksforgeeks.org


Geeks Premier League

Related
Javascript Program to Check if a given string is Pangram or not Javascript Program to Check if a given string is Pangram or not
7th Constitutional Amendment Act - Seventh Amendment Act 7th Constitutional Amendment Act - Seventh Amendment Act
Vue.js Array Change Detection Vue.js Array Change Detection
Testing REST API with Postman and curl Testing REST API with Postman and curl
FastAPI - FastAPI Event Handlers FastAPI - FastAPI Event Handlers

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
13