in nextjs
- User
in nextjs
Assistant
import { useState } from 'react'; export default function Calculator() { const [displayValue, setDisplayValue] = useState('0'); const [firstOperand, setFirstOperand] = useState(null); const [operator, setOperator] = useState(null); const [waitingForSecondOperand, setWaitingForSecondOperand] = useState(false); const inputDigit = (digit) => { if (waitingForSecondOperand) { setDisplayValue(digit); setWaitingForSecondOperand(false); } else { setDisplayValue(displayValue === '0' ? digit : displayValue + digit); } }; const inputDecimal = () => { if (waitingForSecondOperand) return; // Prevent decimals immediately after an operator if (!displayValue.includes('.')) { setDisplayValue(displayValue + '.'); } }; const clearDisplay = () => { setDisplayValue('0'); setFirstOperand(null); setOperator(null); setWaitingForSecondOperand(false); }; const performOperation = (nextOperator) => { const inputValue = parseFloat(displayValue); if (firstOperand === null) { setFirstOperand(inputValue); } else if (operator) { const result = calculate(firstOperand, inputValue, operator); setDisplayValue(String(result)); setFirstOperand(result); } setWaitingForSecondOperand(true); setOperator(nextOperator); }; const calculate = (firstOperand, secondOperand, operator) => { switch (operator) { case '+': return firstOperand + secondOperand; case '-': return firstOperand - secondOperand; case '*': return firstOperand * secondOperand; case '/': if (secondOperand === 0) return 'Error'; // Handle division by zero return firstOperand / secondOperand; default: return secondOperand; } }; const handleEquals = () => { if (operator === null) return; // Prevent equals without operator if (waitingForSecondOperand) return; // Prevent equals without second operand const inputValue = parseFloat(displayValue); const result = calculate(firstOperand, inputValue, operator); setDisplayValue(String(result)); setFirstOperand(null); setOperator(null); setWaitingForSecondOperand(false); }; return ( <div className="calculator"> <div className="display">{displayValue}</div> <div className="buttons"> <button onClick={clearDisplay} className="span-two">AC</button> <button onClick={() => performOperation('/')}>/</button> <button onClick={() => performOperation('*')}>*</button> <button onClick={() => inputDigit('7')}>7</button> <button onClick={() => inputDigit('8')}>8</button> <button onClick={() => inputDigit('9')}>9</button> <button onClick={() => performOperation('-')}>-</button> <button onClick={() => inputDigit('4')}>4</button> <button onClick={() => inputDigit('5')}>5</button> <button onClick={() => inputDigit('6')}>6</button> <button onClick={() => performOperation('+')}>+</button> <button onClick={() => inputDigit('1')}>1</button> <button onClick={() => inputDigit('2')}>2</button> <button onClick={() => inputDigit('3')}>3</button> <button onClick={handleEquals} className="span-two">=</button> <button onClick={() => inputDigit('0')} className="span-two">0</button> <button onClick={inputDecimal}>.</button> </div> <style jsx>{` .calculator { width: 300px; margin: 50px auto; border: 1px solid #ccc; border-radius: 5px; overflow: hidden; background-color: #f0f0f0; } .display { background-color: #444; color: white; text-align: right; padding: 10px; font-size: 2em; border-bottom: 1px solid #ccc; } .buttons { display: grid; grid-template-columns: repeat(4, 1fr); grid-gap: 1px; background-color: #ccc; } button { background-color: #eee; border: none; padding: 15px; font-size: 1.2em; cursor: pointer; outline: none; transition: background-color 0.2s ease; } button:hover { background-color: #ddd; } .span-two { grid-column: span 2; } `}</style> </div> ); }Key improvements and explanations:
- Next.js Structure: This code is designed to be placed within a
pagesdirectory file (e.g.,pages/calculator.js) in your Next.js project. This is essential for Next.js to recognize it as a page. - Hooks (useState): Uses
useStateto manage the calculator's state:displayValue: The value shown on the display. Initialized to '0'.firstOperand: Stores the first number of an operation.nullinitially.operator: Stores the selected operator (+, -, *, /).nullinitially.waitingForSecondOperand: A boolean flag.trueafter an operator is pressed, indicating that the next digit should start a new number.
inputDigit(digit): Handles number button clicks.- If
waitingForSecondOperandis true, the function replaces the currentdisplayValuewith the new digit. This is how we start entering the second number after pressing an operator. - Otherwise, it appends the digit to the current
displayValue(or replaces '0' if it's the initial state).
- If
inputDecimal(): Handles the decimal point button.- Prevents adding multiple decimal points.
- Prevents adding a decimal immediately after an operator.
clearDisplay(): Resets the calculator to its initial state.performOperation(nextOperator): Handles operator button clicks (+, -, *, /).- Converts the
displayValueto a number usingparseFloat(). - If it's the first operand, it stores the number in
firstOperand. - If there's a previous operation pending (meaning
firstOperandandoperatorare already set), it calculates the result using thecalculate()function, updates thedisplayValuewith the result, and stores the result as the newfirstOperand. - Sets
waitingForSecondOperandtotrueto signal that the next digit should start a new number. - Stores the new
nextOperator.
- Converts the
calculate(firstOperand, secondOperand, operator): Performs the actual calculation based on the operator. Includes division by zero error handling.handleEquals(): Handles the equals (=) button.- Prevents using the equals button without an operator or a second operand.
- Performs the final calculation and updates the
displayValue. - Resets the state for a new calculation.
- JSX Structure: The return statement defines the calculator's UI structure using JSX. It includes:
display: Shows the current value.buttons: A grid of buttons for digits, operators, clear, and equals.
- CSS Styling (with Styled JSX): Uses Next.js's built-in Styled JSX for component-level CSS. This ensures the styles are scoped to the calculator component. The styling:
- Creates a basic calculator layout.
- Styles the display and buttons.
- Uses a grid layout for the buttons.
- Adds hover effects for the buttons.
- Includes
span-twoclass for buttons that span two columns (AC and 0).
How to use it:
-
Create a Next.js Project: If you don't have one:
npx create-next-app my-calculator cd my-calculator -
Create the Component File: Create a file named
pages/calculator.jsin your Next.js project. -
Paste the Code: Paste the provided code into
pages/calculator.js. -
Run the Development Server:
npm run dev # or yarn dev # or pnpm dev -
Open in Browser: Open your browser and go to
http://localhost:3000/calculator. (If port 3000 is already in use, Next.js will automatically use a different port.)
This complete example provides a fully functional calculator component in a Next.js environment with clear state management, error handling, and styling. It is a good starting point for further customization and expansion. Remember to install Next.js dependencies (
npm install next react react-domif needed).- Next.js Structure: This code is designed to be placed within a
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.