React.js Age Calculator From Date of Birth in Browser Using TypeScript Full Project For Beginners

You are currently viewing React.js Age Calculator From Date of Birth in Browser Using TypeScript Full Project For Beginners

 

Welcome folks today in this blog post we will be building a react.js age calculator from date of birth in browser using typescript. All the full source code of the application is shown below.

 

 

Get Started

 

 

In order to get started you need to make an index.html file and copy paste the following code

 

index.html

 

<!DOCTYPE html>
<html>
    <head>
        <title>React.js Age Calculator in TypeScript</title>
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <div id="root">

        </div>
    </body>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.development.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.development.js"></script>
    <script src="script.js"></script>
</html>

 

 

Now make a style.css file and copy paste the following code

 

style.css

 

@import url('https://fonts.googleapis.com/css?family=Merienda+One');

body{
   background-image: linear-gradient(43deg, #2f4e31 25%, #4a3129 49%, #542e5a 93%);
   min-height:calc(100vh - 16px);
   color:#fff;
   font-family: 'Merienda One', cursive;
}

#container{
  width:100%;
  height:100%;
  table{
    margin: 0 auto;
    border-spacing: 12px;
    border: 4px dashed;
    padding: 18px;
    h2{
     text-transform: uppercase;
      margin: 0;
      padding: 0;
      background-image: url(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTsSKLt4iKH3QPxeZFYmxwOVKZl84p0t1EQVvBMR5OlRbJioE_f);
      -webkit-text-fill-color: transparent;
      -webkit-background-clip: text;
      font-size: 41px;
    }
    span{
      padding-right:20px;
      font-size:15px;
      font-weight:bold;
    }
    button{
      font-size: 15px;
      font-weight:bold;
      padding: 10px;
      width: 100%;
      border:none;
      background-image: linear-gradient(43deg, #1b1b1b 0%, #824b39 46%, #210525 100%);
      color:#fff;
      border:none;
      box-shadow:0 0 8px 0 #686869;
      border-radius: 12px;
    }
    input{
      padding:5px 10px;
      border-radius: 12px;
      border:none;
    }
    .result{
      text-align:center;
      font-size:15px;
      font-weight:bold;
    }
  } 
}

 

 

And now make a script.js file and copy paste the following code

 

script.js

 

class AgeCalculator extends React.Component {
    state = {};
    public render(): JSX.Element {
        return (
            <div id="container">
                <table>
                    <thead>
                        <tr>
                            <th colSpan={2}><h2>Age Calculator</h2></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            <td><span>Date of birth: </span></td>
                            <td><input ref={(r) => this.dob = r} type="date" /></td>
                        </tr>
                        <tr>
                            <td colSpan={2}>
                                <button onClick={this.calculateAge}>Calculate age</button>
                            </td>
                        </tr>
                        <tr>
                            <td colSpan={2}><div className="result">{this.state.ageString}</div></td>
                        </tr>
                    </tbody>
                </table>
            </div>
        );
    }

    private calculateAge = (): void => {
        const dateString: string = this.dob.value;
        const now: Date = new Date();

        const yearNow: number = now.getFullYear();
        const monthNow: number = now.getMonth();
        const dateNow: number = now.getDate();

        const dob: Date = new Date(dateString);

        const yearDob: number = dob.getFullYear();
        const monthDob: number = dob.getMonth();
        const dateDob: number = dob.getDate();

        let yearAge: number = yearNow - yearDob;
        let monthAge: number;

        if (monthNow >= monthDob) {
            monthAge = monthNow - monthDob;
        } else {
            yearAge--;
            monthAge = 12 + monthNow - monthDob;
        }

        let dateAge: number;
        if (dateNow >= dateDob) {
            dateAge = dateNow - dateDob;
        } else {
            monthAge--;
            dateAge = 31 + dateNow - dateDob;

            if (monthAge < 0) {
                monthAge = 11;
                yearAge--;
            }
        }

        const age = {
            years: yearAge,
            months: monthAge,
            days: dateAge
        };

        const yearString: string = (age.years > 1) ? "years" : "year";
        const monthString: string = (age.months > 1) ? " months" : " month";
        const dayString: string = (age.days > 1) ? " days" : " day";

        let ageString: string = "";

        if ((age.years > 0) && (age.months > 0) && (age.days > 0)) {
            ageString = age.years + yearString + ", " + age.months + monthString + ", and " + age.days + dayString + " old.";
        } else if ((age.years === 0) && (age.months === 0) && (age.days > 0)) {
            ageString = "Only " + age.days + dayString + " old!";
        } else if ((age.years > 0) && (age.months === 0) && (age.days === 0)) {
            ageString = age.years + yearString + " old. Happy Birthday!!";
        } else if ((age.years > 0) && (age.months > 0) && (age.days === 0)) {
            ageString = age.years + yearString + " and " + age.months + monthString + " old.";
        } else if ((age.years === 0) && (age.months > 0) && (age.days > 0)) {
            ageString = age.months + monthString + " and " + age.days + dayString + " old.";
        } else if ((age.years > 0) && (age.months === 0) && (age.days > 0)) {
            ageString = age.years + yearString + " and " + age.days + dayString + " old.";
        } else if ((age.years === 0) && (age.months > 0) && (age.days === 0)) {
            ageString = age.months + monthString + " old.";
        } else {
            ageString = "Oops! Could not calculate age!";
        }

        this.setState({ ageString });
    };
}

ReactDOM.render(<AgeCalculator />, document.getElementById("root"));

 

 

Now if you open index.html file inside the browser you will see the below screenshot

 

Leave a Reply