DEV Community

Cover image for Let's Build an Age Calculator with React Hooks in Nextjs
AULNEIA VOEN
AULNEIA VOEN

Posted on

Let's Build an Age Calculator with React Hooks in Nextjs

In this tutorial, we’re going to create a simple Age Calculator using React Hooks. This project is a great way to practice your React skills while building something useful. So, let’s dive in!

Setting Up the Project

First, we need to set up our development environment. We’ll use Create React App to quickly get our project up and running. Open your terminal and run the following command:

npx create-react-app age-calculator
cd age-calculator
Enter fullscreen mode Exit fullscreen mode

Once the setup is complete, open the project in your favorite code editor.

Styling the Application

To make our Age Calculator look nice, we use Tailwind CSS for styling. If you haven't set it up yet, you can follow the Tailwind CSS installation guide to add it to your project.

Importing React Hooks

Next, we'll import the useState hook from React. This will help us manage the state of
our application, specifically the user's input (their birth date) and the calculated age.

At the top of your main component file (let's say App.js), add the following import:

import  { useState }  from  'react';
Enter fullscreen mode Exit fullscreen mode

Creating the Age Calculation Logic

Now, let's write the function that will calculate the age based on the birth date. We'll create a function called calculateAge that takes the birth date as an argument and returns the calculated age.

Here's how you can implement it:

const calculateAge = (birthDate) => {
  const today = new Date();
  const birth = new Date(birthDate);
  let age = today.getFullYear() - birth.getFullYear();
  const m = today.getMonth() - birth.getMonth();
  if (m < 0 || (m === 0 && today.getDate() < birth.getDate())) {
    age--;
  }
  return age;
};
Enter fullscreen mode Exit fullscreen mode

Building the User Interface

Next, we'll create a simple user interface. We'll need an input field for the user to enter their birth date and a button to trigger the age calculation. We can also display the calculated age once it's determined.

Here's a basic structure for our component:

return (
  <div className="bg-black text-white p-8 rounded-lg shadow-md">
    <h1 className="text-2xl font-bold mb-4">Age Calculator</h1>
    <input
      type="date"
      value={birthDate}
      onChange={(e) => setBirthDate(e.target.value)}
      className="bg-gray-800 text-white border-2 border-gray-700 p-2 rounded-md"
    />
    <button
      onClick={handleCalculate}
      className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mt-4"
    >
      Calculate Age
    </button>
    {age !== null && (
      <p className="text-lg mt-4">Your age is: {age}</p>
    )}
  </div>
);
Enter fullscreen mode Exit fullscreen mode

Completed Code and Testing the Application

Here is the completed code

import { useState, useEffect } from 'react';

function AgeCalculator() {
  const [birthDate, setBirthDate] = useState('');
  const [age, setAge] = useState(null);

  const handleCalculate = () => {
    const calculatedAge = calculateAge(birthDate);
    setAge(calculatedAge);
  };

  useEffect(() => {
    if (birthDate) {
      const calculatedAge = calculateAge(birthDate);
      setAge(calculatedAge);
    }
  }, [birthDate]);

  return (
    <div className="bg-black text-white p-8 rounded-lg shadow-md">
      <h1 className="text-2xl font-bold mb-4">Age Calculator</h1>
      <input
        type="date"
        value={birthDate}
        onChange={(e) => setBirthDate(e.target.value)}
        className="bg-gray-800 text-white border-2 border-gray-700 p-2 rounded-md"
      />
      <button
        onClick={handleCalculate}
        className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded mt-4"
      >
        Calculate Age
      </button>
      {age !== null && (
        <p className="text-lg mt-4">Your age is: {age}</p>
      )}
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now that we have everything in place, let's run the application. In your terminal, use the following command:

npm start
Enter fullscreen mode Exit fullscreen mode

Open your browser and navigate to http://localhost:3000. Enter your birth date and click the "Calculate Age" button. You should see your age displayed on the screen!

Conclusion

Congratulations! You've just built a simple Age Calculator using React Hooks. This project not only helps you practice your React skills but also gives you a functional tool that you can share with others. Here's the link to the working project: age-calculator Feel free to expand on this project by adding features like age in months or days, or even styling it further.

Happy coding, and I can't wait to see what you create next!

Top comments (0)