Open In App

Build a Calculator with React, Tailwind, and Django

Last Updated : 23 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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 :

Django

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.

Python3




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’.

Python3




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’ .

Python3




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.

Python3




MIDDLEWARE = [
...............................  ......................... ...............
............................ .........................  .....................
'corsheaders.middleware.CorsMiddleware',
]
 
CORS_ALLOWED_ORIGINS = [
]
 
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 :

react

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 :

Build a Calculator with React, Tailwind, and Django

Video Demonstration



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads