Create a Counter App Using React, Tailwind and Django Framework
Last Updated :
28 Apr, 2025
This article will guide you in creating a Counter using React and Tailwind with the Django Framework. We’ll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the Counter in Python using the Django Framework.
What is Counter App?
The Counter app is a straightforward tool designed for easy numeric tracking. Its minimalist interface prominently features a displayed number, accompanied by two intuitive buttons. Users can effortlessly increase the count by pressing the increment button or decrease it with the decrement button, providing a seamless and user-friendly experience for managing numerical values on the go.
Counter using React and Tailwind using Django Framework
Here, is the step-by-step implementation of Counter using React, Tailwind, and Django Framework. Here, we will cover the article in 2 parts, frontend and then backend.
Backend Using Django
To start the project and app use this command
django-admin startproject calculator_backend
cd calculator_backend
python manage.py startapp counter
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',
'rest_framework',
'corsheaders',
'counter'
]
To install the corsheaders run the below command in your terminal:
pip install django-cors-headers
File Structure
File StrcutureSetting Necessary Files
models.py : below code defines a Django model named "Counter" with a single field "value" of type IntegerField, set with a default value of 50. This model can be used to represent a counter with an initial value 50.
Python3
# /counter/models.py
from django.db import models
class Counter(models.Model):
value = models.IntegerField(default=50)
views.py :In below code Django REST Framework views define API endpoints for retrieving, incrementing, decrementing, and resetting a counter. The counter is represented by the "Counter" model, and the operations are performed based on HTTP POST requests, with corresponding responses containing messages and the updated counter value.
Python3
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from django.shortcuts import get_object_or_404
from .models import Counter
from .serializers import CounterSerializer
@api_view(['GET'])
def get_counter(request):
counter_instance = Counter.objects.first()
if counter_instance is None:
counter_instance = Counter.objects.create(value=50)
serializer = CounterSerializer(counter_instance)
return Response(serializer.data, status=status.HTTP_200_OK)
@api_view(['POST'])
def increment_counter(request):
counter = get_object_or_404(Counter, pk=1)
counter.value += 1
counter.save()
serializer = CounterSerializer(counter)
return Response({'message': 'Counter incremented successfully', 'value': serializer.data['value']})
@api_view(['POST'])
def decrement_counter(request):
counter = get_object_or_404(Counter, pk=1)
counter.value -= 1
counter.save()
serializer = CounterSerializer(counter)
return Response({'message': 'Counter decremented successfully', 'value': serializer.data['value']})
@api_view(['POST'])
def reset_counter(request):
counter = get_object_or_404(Counter, pk=1)
counter.value = 0
counter.save()
serializer = CounterSerializer(counter)
return Response({'message': 'Counter reset successfully', 'value': serializer.data['value']})
serializers.py : In below code Django REST Framework serializer, "CounterSerializer," is configured to serialize the "Counter" model, including only the 'value' field. It enables conversion between the Counter model instances and their JSON representations for use in the API views.
Python3
# /counter/serializers.py
from rest_framework import serializers
from .models import Counter
class CounterSerializer(serializers.ModelSerializer):
class Meta:
model = Counter
fields = ['value']
counter_backend/urls.py : In below code Django URL configuration includes the default admin URLs and routes any URL starting with 'api/' to the URLs defined in the 'counter.urls' module, allowing the integration of the counter app's API endpoints.
Python3
# /counter_backend/urls.py
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('counter.urls')), # Include counter_app URLs
]
counter/urls.py : In below code Django URL configuration for the 'counter' app maps specific paths to corresponding views: 'get-counter/' for retrieving the counter, 'increment-counter/' for incrementing it, 'decrement-counter/' for decrementing it, and 'reset-counter/' for resetting it
Python3
# counter/urls.py
from django.urls import path
from .views import get_counter, increment_counter, decrement_counter,reset_counter
urlpatterns = [
path('get-counter/', get_counter, name='get_counter'),
path('increment-counter/', increment_counter, name='increment_counter'),
path('decrement-counter/', decrement_counter, name='decrement_counter'),
path('reset-counter/', reset_counter, name='reset_counter'),
]
Frontend Using React + Tailwind
To start the project in react use this command
npx create-react-app counter_frontend
cd counter_frontend
Install the necessary library tailwindcss using the below command
npm install tailwindcss
File Structure
File StructureCreating User InterFace
App.css: In below code this is a set of CSS styles for a React application or website. It includes styles for centering the content, setting the height and animation for a logo, defining the appearance of the header, and specifying colors and fonts. The keyframes section defines a spin animation for the logo, which rotates continuously from 0 to 360 degrees.
CSS
.App {
text-align: center;
}
.App-logo {
height: 40vmin;
pointer-events: none;
}
@media (prefers-reduced-motion: no-preference) {
.App-logo {
animation: App-logo-spin infinite 20s linear;
}
}
.App-header {
background-color: #282c34;
min-height: 100vh;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
font-size: calc(10px + 2vmin);
color: white;
}
.App-link {
color: #61dafb;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
App.js: In below code React component, 'Counter.js', uses the state hook to manage a counter value, fetches the initial value from a Django API endpoint using Axios in the 'useEffect' hook, and provides buttons to increment, decrement, and reset the counter through corresponding API calls. The component's UI is styled with Tailwind CSS.
JavaScript
// src/components/Counter.js
import React, { useState, useEffect } from 'react';
import axios from 'axios'
const App = () => {
const [counterValue, setCounterValue] = useState(50);
useEffect(() => {
axios.get('http://127.0.0.1:8000/api/get-counter/').then(res => setCounterValue(res.data.value))
},[])
const handleIncrement = () => {
axios.post('http://127.0.0.1:8000/api/increment-counter/').then(res => setCounterValue(res.data.value))
}
const handleDecrement = () => {
axios.post('http://127.0.0.1:8000/api/decrement-counter/').then(res => setCounterValue(res.data.value))
}
const handleReset = () => {
axios.post('http://127.0.0.1:8000/api/reset-counter/').then(res => setCounterValue(res.data.value))
}
return (
<div className='p-40 max-w-3xl mx-auto flex space-x-4'>
<button className='bg-blue-500 text-white p-4 rounded-lg' onClick={handleIncrement}>Increment</button>
<p className='border shadow-md max-w-fit p-6 rounded-lg text-2xl'>Counter Value: {counterValue}</p>
<button className='bg-red-500 text-white p-4 rounded-lg' onClick={handleDecrement}>Decrement</button>
<button className='bg-green-400 p-4 px-10 rounded-lg' onClick={handleReset}>Reset</button>
</div>
);
};
export default App;
index.css: below code lines import Tailwind CSS base, components, and utilities styles, facilitating the use of predefined utility classes in your project's stylesheets.
CSS
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';
index.js: This code sets up a React root using ReactDOM's `createRoot` function, renders the `<App />` component inside a `<React.StrictMode>`, and includes a call to `reportWebVitals` for performance measurement. The application's main entry point is 'index.js'.
JavaScript
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
Deployement of the Project
Run the server with the help of following command:
python3 manage.py runserver
npm start
Output
Create a Counter using React and Tailwind using Django Framework
Similar Reads
Build a Contact form Using Django, React and tailwind This article will guide you in creating a Contact form Using Django, React, and tailwind. Weâll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the Contact form. Build a Contact form Using Django, React and TailwindHere, is the step-by-
5 min read
Build a To-Do application Using Django, React and Tailwind This article will guide you in creating a To-Do application using React and Tailwind with the Django Framework. Weâll explore the integration of Django, React, and Tailwind, and go through the step-by-step process of implementing the To-Do application. What is a To-Do application?A To-Do application
6 min read
Create Progress Bar Component using React and Tailwind CSS A progress bar is a visual representation of progress in a process. It is commonly used in web applications to indicate the completion status of an operation. In this article, we will learn how to create a progress bar component in React using Tailwind CSS for styling.PrerequisitesJavaScriptReactTai
2 min read
Create Category Previews Using React And Tailwind CSS In modern web development creating visually appealing and functional components is essential for enhancing user experience. The goal is to showcase categories with distinct icons and a stylish green background using Tailwinds utility classes for a streamlined and responsive design.This article focus
4 min read
Create Banners using React and Tailwind CSS We will build a responsive banner component using React and Tailwind CSS. Tailwind CSS allows us to create highly customizable and modern UI components with minimal effort. The banner will include a heading and subheading and a call to action button styled for responsiveness and accessibility.Prereq
3 min read
Create Logo Clouds using React and Tailwind CSS A Logo Cloud is a webpage section that displays logos of partners, sponsors, clients, or technologies in a visually appealing way. This component is often used to establish credibility or showcase affiliations. Using React and Tailwind CSS you can create a responsive and customizable logo cloud that
3 min read
Create a Weather app using React and Tailwind React JS is a very famous library for front-end development. In this article, we will walk through the process of building a weather app using React, a popular JavaScript library for building user interfaces(UI). Here we also use Tailwind CSS, a utility-first CSS framework. Here we also use a weathe
5 min read
Create FAQs using React and Tailwind CSS A Frequently Asked Questions section is a common feature found on websites and applications that helps users find answers to common queries in an organized manner. A well-designed FAQ can improve user experience reduce support requests and provide users with quick and easy access to helpful informat
5 min read
Create Header using React and Tailwind CSS In modern web development building responsive and customizable user interfaces is crucial. One of the essential elements of any web application is the header which typically contains navigation links branding or other important controls. we will create a responsive header section using React and Tai
4 min read
E-commerce Website using Tailwind and React using Django Our e-commerce website, "ECOM," aims to offer users a smooth online shopping experience. We use Tailwind CSS for styling, React for interactive user interfaces, and Django for a strong backend. Shopify features a wide range of products across different categories, with functionalities like user auth
6 min read