DEV Community

Cover image for How to Build a Hijri Age Calculator in MERN
SaudiBytes
SaudiBytes

Posted on • Edited on

How to Build a Hijri Age Calculator in MERN

The MERN stack (MongoDB, Express.js, React, Node.js) is a powerful combination for building dynamic web applications. In this blog post, we’ll walk through creating a Hijri Age Calculator that calculates a user’s age based on their birth date in the Hijri (Islamic) calendar. The app will allow users to input their birth date, convert it to the Hijri calendar, and display their age. We’ll use a library like hijri-date for Hijri date conversions and integrate it into a MERN application.

Prerequisites

  • Basic knowledge of JavaScript, React, Node.js, and MongoDB.
  • Node.js and MongoDB installed on your system.
  • A code editor like VS Code.

Project Setup

1. Initialize the Backend (Node.js + Express.js)

Create a project directory and set up the backend.

mkdir hijri-age-calculator
cd hijri-age-calculator
mkdir backend
cd backend
npm init -y
npm install express mongoose hijri-date cors dotenv
Enter fullscreen mode Exit fullscreen mode

Create a basic Express server in backend/server.js:

 const express = require('express'); const mongoose = require('mongoose'); const cors = require('cors'); const { HijriDate } = require('hijri-date');

const app = express(); app.use(cors()); app.use(express.json());

mongoose.connect('mongodb://localhost/hijri-age-calculator', { useNewUrlParser: true, useUnifiedTopology: true, }).then(() => console.log('MongoDB connected'));

// API to calculate Hijri age app.post('/api/calculate-age', (req, res) => { const { gregorianDate } = req.body; const birthDate = new Date(gregorianDate); const hijriBirthDate = new HijriDate(birthDate); const today = new HijriDate(); const age = today.year - hijriBirthDate.year; res.json({ hijriBirthDate: hijriBirthDate.toString(), age }); });

const PORT = process.env.PORT || 5000; app.listen(PORT, () => console.log(Server running on port ${PORT}));

Enter fullscreen mode Exit fullscreen mode

2. Set Up MongoDB

Ensure MongoDB is running locally. The app currently doesn’t use MongoDB for storage, but you can extend it to save user data. Create a .env file in the backend folder:

MONGODB_URI=mongodb://localhost/hijri-age-calculator PORT=5000
Enter fullscreen mode Exit fullscreen mode

3. Initialize the Frontend (React)

In the project root, create a React app:

npx create-react-app frontend
cd frontend
npm install axios
Enter fullscreen mode Exit fullscreen mode

4. Build the React Frontend

Create a component to handle user input and display the calculated age. Replace frontend/src/App.js with:

import React, { useState } from 'react';
import axios from 'axios';
import './App.css';

function App() {
  const [gregorianDate, setGregorianDate] = useState('');
  const [result, setResult] = useState(null);

  const calculateAge = async (e) => {
    e.preventDefault();
    try {
      const response = await axios.post('http://localhost:5000/api/calculate-age', {
        gregorianDate,
      });
      setResult(response.data);
    } catch (error) {
      console.error('Error calculating age:', error);
    }
  };

  return (
    <div className="App">
      <h1>Hijri Age Calculator</h1>
      <form onSubmit={calculateAge}>
        <label>
          Enter your birth date (YYYY-MM-DD):
          <input
            type="date"
            value={gregorianDate}
            onChange={(e) => setGregorianDate(e.target.value)}
            required
          />
        </label>
        <button type="submit">Calculate Age</button>
      </form>
      {result && (
        <div>
          <h3>Results:</h3>
          <p>Hijri Birth Date: {result.hijriBirthDate}</p>
          <p>Age: {result.age} years</p>
        </div>
      )}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode
  1. Running the Application Start the backend:
cd backend
node server.js
Enter fullscreen mode Exit fullscreen mode

Start the frontend:

cd frontend
npm start
Enter fullscreen mode Exit fullscreen mode

Open your browser to http://localhost:3000. Enter a birth date in the format YYYY-MM-DD, and the app will display the Hijri birth date and age.

How It Works

Backend: The Express server uses the hijri-date library to convert a Gregorian date to a Hijri date and calculates the age based on the year difference.

Frontend: The React app sends the user’s input to the backend via an API call using axios and displays the response.
MongoDB: While not used for storage in this example, you can extend the app to save user calculations in MongoDB for history tracking.

Extending the App

Save Calculations: Add a MongoDB schema to store user inputs and results.
Improved Age Calculation: Account for months and days in the age calculation for precision.
Styling: Enhance the UI with a CSS framework כמו Tailwind CSS.
Validation: Add input validation to ensure valid dates.
This project demonstrates how to integrate a Hijri date conversion library into a MERN stack application. You can expand it further based on your needs!

Top comments (0)