Make me an calculator in next js
- User
Make me an calculator in next js
- Assistant
Make me an calculator in next js
Certainly! Let's build a simple calculator using Next.js, a React framework that enables server-side rendering and static site generation. This calculator will perform basic arithmetic operations like addition, subtraction, multiplication, and division.
Prerequisites:
Create a New App
Open your terminal and run the following command to create a new Next.js application:
npx create-next-app calculator-app
This command sets up a new Next.js project in a folder named calculator-app.
Navigate to the Project Directory
cd calculator-app
Start the Development Server
Run the development server with:
npm run dev
Open your browser and go to http://localhost:3000 to see the default Next.js page.
Create a Components Directory
Inside your project, create a components directory to keep your components organized:
mkdir components
Create the Calculator Component
In the components directory, create a new file called Calculator.js:
touch components/Calculator.js
Implement the Calculator Logic
Open components/Calculator.js and add the following code:
// components/Calculator.js
import { useState } from 'react';
import { evaluate } from 'mathjs';
const Calculator = () => {
const [expression, setExpression] = useState('');
const [result, setResult] = useState(null);
const handleButtonClick = (value) => {
setExpression((prev) => prev + value);
};
const handleClear = () => {
setExpression('');
setResult(null);
};
const handleBackspace = () => {
setExpression((prev) => prev.slice(0, -1));
};
const handleCalculate = () => {
try {
const evalResult = evaluate(expression);
setResult(evalResult);
} catch {
setResult('Error');
}
};
return (
<div className="calculator">
<div className="display">
{expression || '0'}
</div>
<div className="buttons">
<button onClick={handleClear}>C</button>
<button onClick={handleBackspace}>←</button>
<button onClick={() => handleButtonClick('/')}>÷</button>
<button onClick={() => handleButtonClick('*')}>×</button>
<button onClick={() => handleButtonClick('7')}>7</button>
<button onClick={() => handleButtonClick('8')}>8</button>
<button onClick={() => handleButtonClick('9')}>9</button>
<button onClick={() => handleButtonClick('-')}>−</button>
<button onClick={() => handleButtonClick('4')}>4</button>
<button onClick={() => handleButtonClick('5')}>5</button>
<button onClick={() => handleButtonClick('6')}>6</button>
<button onClick={() => handleButtonClick('+')}>+</button>
<button onClick={() => handleButtonClick('1')}>1</button>
<button onClick={() => handleButtonClick('2')}>2</button>
<button onClick={() => handleButtonClick('3')}>3</button>
<button onClick={handleCalculate} className="equal">=</button>
<button onClick={() => handleButtonClick('0')} className="zero">0</button>
<button onClick={() => handleButtonClick('.')}>.</button>
</div>
{result !== null && (
<div className="result">
Result: {result}
</div>
)}
<style jsx>{`
.calculator {
width: 300px;
margin: 50px auto;
padding: 20px;
border: 2px solid #ccc;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
background-color: #f9f9f9;
}
.display {
height: 60px;
font-size: 32px;
padding: 10px;
background-color: #eaeaea;
margin-bottom: 10px;
text-align: right;
overflow: hidden;
white-space: nowrap;
}
.buttons {
display: flex;
flex-wrap: wrap;
}
.buttons button {
width: 70px;
height: 70px;
margin: 5px;
font-size: 24px;
border: none;
border-radius: 5px;
cursor: pointer;
background-color: #fff;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.buttons button:hover {
background-color: #f0f0f0;
}
.equal {
background-color: #28a745;
color: #fff;
}
.equal:hover {
background-color: #218838;
}
.zero {
flex: 1;
}
.result {
margin-top: 20px;
font-size: 24px;
text-align: right;
}
`}</style>
</div>
);
};
export default Calculator;
Explanation:
State Variables:
expression: Stores the mathematical expression input by the user.result: Stores the evaluated result of the expression.Functions:
handleButtonClick(value): Updates the expression when a button is clicked.handleClear(): Resets the expression and result.handleBackspace(): Removes the last character from the expression.handleCalculate(): Evaluates the expression using mathjs's evaluate function.UI Components:
For safe expression evaluation, we'll use the mathjs library.
Install mathjs
Run the following command in your terminal:
npm install mathjs
Modify pages/index.js
Replace the content of pages/index.js with:
// pages/index.js
import Head from 'next/head';
import Calculator from '../components/Calculator';
export default function Home() {
return (
<div>
<Head>
<title>Next.js Calculator</title>
<meta name="description" content="A simple calculator built with Next.js" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main>
<h1 style={{ textAlign: 'center', marginTop: '20px' }}>Next.js Calculator</h1>
<Calculator />
</main>
</div>
);
}
Start the Development Server
Ensure your development server is running:
npm run dev
View in Browser
Go to http://localhost:3000 in your browser. You should see your calculator app.
Try performing some calculations:
12 + 7 * 3.= button to evaluate.C to clear and ← to delete the last character.Feel free to enhance the calculator:
Once you're satisfied with your calculator, you can deploy it online.
Deploying to Vercel
Vercel is a platform by the creators of Next.js that's perfect for deploying Next.js applications.
Install Vercel CLI (if not already installed):
npm install -g vercel
Deploy the App:
vercel
Follow the prompts to link or create a project.
Alternative Hosting
You can also export the app as a static site or deploy it using other hosting services that support Next.js.
Using eval() is generally unsafe due to security risks like code injection. By using mathjs, we safely parse and evaluate mathematical expressions.
You've successfully created a calculator using Next.js! This project showcases how to handle state, events, and user interactions in a React-based framework.
Additional Resources:
If you have any questions or need further assistance, feel free to ask!
Not yet included in a published release.