Build a Calculator with React, Tailwind, and Django
Last Updated :
07 Apr, 2025
This article will guide you in creating a calculator 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 calculator.
What is a Calculator?
A calculator is a device or tool designed for performing mathematical calculations. It typically consists of numerical buttons, mathematical operators (such as addition, subtraction, multiplication, and division), and a display screen. Calculators are used to quickly and accurately perform various mathematical operations, ranging from simple arithmetic to more complex calculations.
Calculator using React, Tailwind, and Django Framework
Here, is the step-by-step implementation of Calculator using React, Tailwind, and Django Framework. Here, we will cover the article into 2 parts, frontend and then backend. To install Django follow these steps.
Backend Using Django
To start the project and app use this command
django-admin startproject calculator_backend
cd calculator_backend
python manage.py startapp calculator
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",
"calculator",
'corsheaders',
]
For install the corsheaders run the below command
pip install django-cors-headers
File Strcutrue :

Setting Necessary Files
views.py : In below code `calculate` view function in this Django code handles POST requests containing a JSON payload with a mathematical expression. The function evaluates the expression using the `eval` function and returns the result as a JSON response. If there's an error during evaluation, it returns an error message.
Python
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json
@csrf_exempt
def calculate(request):
if request.method == 'POST':
data = json.loads(request.body)
expression = data.get('expression', '')
try:
result = str(eval(expression))
return JsonResponse({'result': result})
except Exception as e:
return JsonResponse({'error': str(e)})
else:
return JsonResponse({'error': 'Invalid request method'})
project/urls.py: here, Django code configures a single URL route, linking the 'calculate/' endpoint to the 'calculate'.
Python
from django.contrib import admin
from django.urls import path,include
from .views import *
urlpatterns = [
path('calculate/', calculate, name = 'calculate'),
]
app/urls.py: Here, Django code defines URL patterns, routing requests to the Django admin interface at '/admin/' and including additional patterns from the 'calculator.urls' .
Python
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('calculator.urls'))
]
settings.py : In settings.py we added the crosheaders Middleware and also the some allowing host for integrating react.
Python
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 calculator_frontend
cd calculator_frontend
Install the necessary library tailwindcss using the below command
npm install tailwindcss
File Structure :

Creating User InterFace
App.css: In below CSS code styles a React application, centering text, setting a rotating animation for the logo, styling the header, and defining link colors. The design is responsive, featuring a rotating logo with reduced motion support.
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: This React code defines a calculator app using Django, React, and TailwindCSS. It utilizes state hooks for managing user input and displaying the calculation result. Functions handle button clicks, clearing input, and triggering calculations through a Django backend. The JSX renders a visually appealing UI with input, buttons, and dynamic styling using TailwindCSS, creating an interactive calculator with integrated frontend and backend functionality.
JavaScript
import React, { useState } from 'react';
import './App.css';
function App() {
// State to manage the user input expression
const [expression, setExpression] = useState('');
// State to store the calculation result
const [result, setResult] = useState('');
// Function to handle button click events and update the expression
const handleButtonClick = (value) => {
setExpression((prev) => prev + value);
};
// Function to clear the last character from the expression
const clear = () => {
const newExpression = expression.slice(0, -1);
setExpression(newExpression);
}
// Function to clear the entire expression
const clearAll = () => {
setExpression('');
}
// Function to handle the calculation when the '=' button is clicked
const handleCalculate = async () => {
try {
// Sending a POST request to the server for calculation
const response = await fetch('http://127.0.0.1:8000/calculate/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ expression }),
});
// Parsing the response and updating the result state
const data = await response.json();
setResult(data.result);
} catch (error) {
console.error('Error calculating:', error);
}
};
// JSX for rendering the Calculator App
return (
<div className="App max-w-3xl mx-auto">
<div>
<h1 className='mt-4 mb-4'>Django + React + TailwindCSS Calculator</h1>
<div className='border border-b-2 p-12 relative rounded-md shadow-sm'>
{/* Input field to display the expression */}
<input
type="text"
value={expression}
className="absolute focus:outline-none left-10 text-lg"
/>
{/* Buttons for Clear and Clear All actions */}
<div className='flex space-x-4 absolute bottom-4 right-4'>
<button onClick={clear} className='bg-red-400 text-sm text-white border rounded-full px-4 py-2'>Clear</button>
<button onClick={clearAll} className='bg-red-400 text-sm text-white border rounded-full px-4 py-2'>Clear All</button>
</div>
{/* Displaying the result */}
<div className='absolute top-3 right-6'>
<h1>{result}</h1>
</div>
</div>
</div>
{/* Grid layout for the calculator buttons */}
<div className="grid grid-cols-4 gap-10 border bg-gray-300 rounded-md p-12 shadow-xl">
{/* Mapping buttons for digits and operators */}
{[7, 8, 9, '/'].map((value) => (
<button className='border p-4 bg-white rounded-full' key={value} onClick={() => handleButtonClick(value)}>
{value}
</button>
))}
{[4, 5, 6, '*'].map((value) => (
<button className='border p-4 bg-white rounded-full' key={value} onClick={() => handleButtonClick(value)}>
{value}
</button>
))}
{[1, 2, 3, '-'].map((value) => (
<button className='border p-4 bg-white rounded-full' key={value} onClick={() => handleButtonClick(value)}>
{value}
</button>
))}
{[0, '.', '=', '+'].map((value) => (
// Special styling for the '=' button
<button className={`${value === '=' && 'border-red-300 border-8'} border p-4 bg-white rounded-full`}
key={value}
onClick={value === '=' ? handleCalculate : () => handleButtonClick(value)}
>
{value}
</button>
))}
</div>
</div>
);
}
export default App;
App.test.js: This test script is checking whether the "learn react" link is rendered in the React component specified by the `App` import. It uses the `render` function from `@testing-library/react` to render the component, and then it uses `screen.getByText` to find an element containing the text "learn react.".
JavaScript
import { render, screen } from '@testing-library/react';
import App from './App';
test('renders learn react link', () => {
render(<App />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
index.css : Below, syntax is configuring Tailwind CSS in a single file, including base styles, components, and utilities to apply the framework's styling to the project.
CSS
@tailwind base;
@tailwind components;
@tailwind utilities;
Deployement of the Project
Run the server with the help of following command:
python3 manage.py runserver
npm start
Output :

Video Demonstration
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 Simple Tip Calculator App with ReactJS
Creating a simple tip calculator app using ReactJS can be good for practicing React state management and components. In this tutorial, we'll create a basic tip calculator app using React.js. The app will allow users to input the bill amount, select a tip percentage and let split the bill, providing
3 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
Build Calculator App Using Django
In this article, we will guide you through the process of creating a calculator app using Django. Our goal is to develop a versatile application capable of performing fundamental mathematical operations such as addition, subtraction, multiplication, and more. By the end of this tutorial, you will ha
3 min read
Build an Authentication System Using Django, React and Tailwind
In this article, we will guide you in building an Authentication system using React and Tailwind with the Django Framework that includes features like sign up, log in, forgot password, and reset password. Weâll explore the integration of Django, React, and Tailwind CSS and go through the step-by-ste
15+ min read
Build a Loan Calculator using Next.js
The Loan Calculator allows users to determine loan amount, interest rate, and tenure, calculate monthly mortgage payments, total loan payments over tenure, and total interest payable. In this article, we will walk you through the process of building a Loan Calculator using Next.js. Let's take a look
4 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
Build a Clock Application using Django and React
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 bui
4 min read
Build a Calculator with VueJS
We'll learn how to build a simple calculator app using Vue.js. A calculator is a fundamental tool for performing mathematical calculations, and building one using Vue.js is a great way to understand the basics of Vue.js components, data binding, and event handling. Step-by-step guide to set up the p
3 min read
Tip Calculator Project Using Django
In this article, we will guide you through the process of creating a Tip Calculator Project using Django. This interactive project requires users to input the bill amount, the desired percentage for the tip, and the number of people splitting the bill. The application will then compute and display t
6 min read