Open In App

Build a Clock Application using Django and React

Last Updated : 26 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

The clock project aims to develop a simple yet functional clock application using modern web technologies. It combines the frontend capabilities of React.js for creating dynamic user interfaces with the styling power of Tailwind CSS for a sleek and responsive design. Additionally, the backend is built using Django, providing a robust framework for managing server-side logic and serving the frontend assets.

Create a Clock using React and Tailwind using the Django Framework

Here, is the step-by-step implementation of Clock using React, Tailwind, and Django Framework. Here, we will cover the article in 2 parts, frontend and then backend. To install Django in Python follow these steps.

Backend Using Django

To start the project and app use this command

django-admin startproject backend
cd backend
python manage.py startapp app

Now add this app to the ‘settings.py’

INSTALLED_APPS = [
"django.contrib.admin",
"django.contrib.auth",
"django.contrib.contenttypes",
"django.contrib.sessions",
"django.contrib.messages",
"django.contrib.staticfiles",
"app",
'corsheaders',
]

For install the corsheaders run the below command

pip install django-cors-headers

File Structure

dfile

Setting Necessary Files

app/views.py: This Django view function, current_time, fetches the current time and formats it as a JSON response with the key “current_time”. It utilizes Django’s JsonResponse to return the time data in a JSON format.

Python3
from django.http import JsonResponse
from datetime import datetime


def current_time(request):
    current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    data = {'current_time': current_time}
    return JsonResponse(data)

backend/urls.py: This Django urlpatterns setup includes routes for both the admin interface

Python3
from django.contrib import admin
from django.urls import path, include
from app import views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.current_time, name="current_time")
]

settings.py : In settings.py we added the crosheaders Middleware and also the some allowing host for integrating react.

Python3
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
]
 
CORS_ALLOWED_ORIGINS = [
    "http://localhost:3000",
]
 
CORS_ALLOW_CREDENTIALS = True

Frontend Using React + Tailwind

To start the project in react use this command

npx create-react-app frontend
cd frontend

Install the necessary library tailwindcss, react-dom and axios using the below command

npm install tailwindcss
npm install react-dom
npm install axios

File Structure :

rfile

Creating User InterFace

App.js: This React component fetches the current time from a Django backend every second using Axios. It then updates the state with the fetched time and displays it as a clock with hour, minute, and second hands rotating dynamically based on the current time.

Javascript
import React, { useState, useEffect } from "react";
import axios from "axios";
import "./App.css";

const App = () => {
  const [time, setTime] = useState(new Date());

  useEffect(() => {
    const interval = setInterval(() => {
      axios
        .get("http://127.0.0.1:8000/")
        .then((response) => {
          const serverTime = new Date(response.data.current_time);
          setTime(serverTime);
        })
        .catch((error) => {
          console.error("Error fetching current time:", error);
        });
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  const getSecondsAngle = () => {
    return 6 * time.getSeconds();
  };

  const getMinutesAngle = () => {
    return 6 * time.getMinutes();
  };

  const getHoursAngle = () => {
    return 30 * time.getHours() + time.getMinutes() / 2;
  };

  return (
    <div className="clock">
      <div
        className="hand hour-hand"
        style={{ transform: `rotate(${getHoursAngle()}deg)` }}
      ></div>
      <div
        className="hand minute-hand"
        style={{ transform: `rotate(${getMinutesAngle()}deg)` }}
      ></div>
      <div
        className="hand second-hand"
        style={{ transform: `rotate(${getSecondsAngle()}deg)` }}
      ></div>
    </div>
  );
};

export default App;

index.js: Below, code renders the React application by mounting the `<App />` component into the HTML element with the id of ‘root’. It utilizes `React.StrictMode` for additional development mode checks.

Javascript
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

tailwind.config.js: This is an empty Tailwind CSS configuration file, providing no additional content, theme extensions, or plugins.

CSS
/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [],
  theme: {
    extend: {},
  },
  plugins: [],
}

App.css : This CSS code styles a clock component with hour, minute, and second hands. It positions them within a circular container and adjusts their sizes and positions accordingly. The hour and minute hands are black, while the second hand is red.

CSS
@import "tailwindcss/base";
@import "tailwindcss/components";
@import "tailwindcss/utilities";

.clock {
  position: relative;
  margin: 20px auto;
  width: 30vw;
  height: 30vw;
  border: 2px solid #000;
  border-radius: 50%;
}

.hand {
  position: absolute;
  background: black;
  border-radius: 10px;
  transform-origin: bottom;
}

.hour-hand {
  width: 1.8%;
  height: 24%;
  top: 25%;
  left: 48.85%;
  opacity: 0.8;
}

.minute-hand {
  width: 1.6%;
  height: 30%;
  top: 19%;
  left: 48.9%;
  opacity: 0.8;
}
.second-hand {
  width: 1%;
  background: red;
  height: 45%;
  top: 4%;
  left: 49.25%;
  opacity: 0.8;
}

Deployement of the Project

Run the server with the help of following command:

python3 manage.py runserver
npm start

Output

Recording-2024-03-18-111358



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads