in nextjs
- User
in nextjs
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
in nextjs
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Okay, let's build a calculator component using Next.js and React. We'll use functional components, hooks (useState, useCallback), and CSS Modules for styling.
Project Structure:
Assume you have a Next.js project set up. You'll need:
components/Calculator.js: The React component for the calculator.components/Calculator.module.css: CSS Module for styling the calculator.pages/index.js: The main page where we'll display the calculator.styles/Home.module.css: Basic page styling (can be customized).1. components/Calculator.js
import React, { useState, useCallback } from 'react';
import styles from './Calculator.module.css'; // Import CSS Module
const Calculator = () => {
// State variables to manage calculator logic
const [display, setDisplay] = useState('0'); // Current value shown on display
const [storedValue, setStoredValue] = useState(null); // Holds the first operand
const [operator, setOperator] = useState(null); // Holds the selected operator (+, -, *, /)
const [waitingForSecondOperand, setWaitingForSecondOperand] = useState(false); // Flag to know if the next digit input should clear the display
// Helper function to perform calculations
const performOperation = useCallback((val, nextOperator) => {
const firstValue = parseFloat(storedValue);
const secondValue = parseFloat(display);
if (isNaN(firstValue) || isNaN(secondValue)) return 'Error'; // Basic validation
let result;
switch (operator) {
case '+':
result = firstValue + secondValue;
break;
case '-':
result = firstValue - secondValue;
break;
case '*':
result = firstValue * secondValue;
break;
case '/':
if (secondValue === 0) return 'Error'; // Handle division by zero
result = firstValue / secondValue;
break;
default:
return secondValue; // Should not happen if operator is set
}
// Handle potential floating point inaccuracies slightly
return parseFloat(result.toPrecision(12));
}, [storedValue, display, operator]);
// Handler for digit button clicks (0-9)
const handleDigitClick = useCallback((digit) => {
if (display === 'Error') return; // Do nothing if currently in error state
if (waitingForSecondOperand) {
// If waiting for the second operand, replace display and reset flag
setDisplay(digit);
setWaitingForSecondOperand(false);
} else {
// Append digit, replace '0' if it's the initial display
setDisplay(display === '0' ? digit : display + digit);
}
}, [display, waitingForSecondOperand]);
// Handler for the decimal point click
const handleDecimalClick = useCallback(() => {
if (display === 'Error') return;
if (waitingForSecondOperand) {
// Start new number with "0."
setDisplay('0.');
setWaitingForSecondOperand(false);
return;
}
// Add decimal only if it doesn't already exist
if (!display.includes('.')) {
setDisplay(display + '.');
}
}, [display, waitingForSecondOperand]);
// Handler for operator button clicks (+, -, *, /)
const handleOperatorClick = useCallback((nextOperator) => {
if (display === 'Error') return;
const inputValue = parseFloat(display);
// If an operator is already pending and we're waiting for the second operand,
// just update the operator (e.g., 5 + * 3 should become 5 * 3).
if (operator && waitingForSecondOperand) {
setOperator(nextOperator);
return;
}
// If storedValue is null, this is the first number entered. Store it.
if (storedValue === null) {
setStoredValue(inputValue);
} else if (operator) {
// If we have a stored value and an operator, perform the pending calculation
const result = performOperation(storedValue, operator);
if (result === 'Error') {
setDisplay('Error');
// Reset state on error
setStoredValue(null);
setOperator(null);
setWaitingForSecondOperand(false);
return;
}
setDisplay(String(result));
setStoredValue(result); // The result becomes the new stored value for chained operations
}
// Set up for the next number input
setWaitingForSecondOperand(true);
setOperator(nextOperator);
}, [display, storedValue, operator, waitingForSecondOperand, performOperation]);
// Handler for the equals button click
const handleEqualsClick = useCallback(() => {
// Only perform calculation if we have an operator, a stored value,
// and the user has entered the second operand (not just clicked an operator)
if (operator === null || storedValue === null || waitingForSecondOperand || display === 'Error') {
return;
}
const result = performOperation(storedValue, operator);
if (result === 'Error') {
setDisplay('Error');
} else {
setDisplay(String(result));
setStoredValue(null); // Clear stored value after equals
}
setOperator(null); // Clear the operator
setWaitingForSecondOperand(true); // Set flag so next digit press clears display
}, [storedValue, operator, waitingForSecondOperand, display, performOperation]);
// Handler for the clear button (AC)
const handleClearClick = useCallback(() => {
setDisplay('0');
setStoredValue(null);
setOperator(null);
setWaitingForSecondOperand(false);
}, []);
// Define the button layout and their properties
// Each object includes label, handler, CSS class, and grid span properties
const buttonLayout = [
// Row 1
{ id: 'clear', label: 'AC', className: `${styles.button} ${styles.clear}`, cols: 2, handler: handleClearClick },
{ id: 'divide', label: '/', className: `${styles.button} ${styles.operator}`, cols: 1, handler: () => handleOperatorClick('/') },
{ id: 'multiply', label: '*', className: `${styles.button} ${styles.operator}`, cols: 1, handler: () => handleOperatorClick('*') },
// Row 2
{ id: 'seven', label: '7', className: styles.button, cols: 1, handler: () => handleDigitClick('7') },
{ id: 'eight', label: '8', className: styles.button, cols: 1, handler: () => handleDigitClick('8') },
{ id: 'nine', label: '9', className: styles.button, cols: 1, handler: () => handleDigitClick('9') },
{ id: 'subtract', label: '-', className: `${styles.button} ${styles.operator}`, cols: 1, handler: () => handleOperatorClick('-') },
// Row 3
{ id: 'four', label: '4', className: styles.button, cols: 1, handler: () => handleDigitClick('4') },
{ id: 'five', label: '5', className: styles.button, cols: 1, handler: () => handleDigitClick('5') },
{ id: 'six', label: '6', className: styles.button, cols: 1, handler: () => handleDigitClick('6') },
{ id: 'add', label: '+', className: `${styles.button} ${styles.operator}`, cols: 1, handler: () => handleOperatorClick('+') },
// Row 4
{ id: 'one', label: '1', className: styles.button, cols: 1, handler: () => handleDigitClick('1') },
{ id: 'two', label: '2', className: styles.button, cols: 1, handler: () => handleDigitClick('2') },
{ id: 'three', label: '3', className: styles.button, cols: 1, handler: () => handleDigitClick('3') },
{ id: 'equals', label: '=', className: `${styles.button} ${styles.equals}`, cols: 1, rows: 2, handler: handleEqualsClick }, // Equals spans 2 rows
// Row 5
{ id: 'zero', label: '0', className: `${styles.button} ${styles.zero}`, cols: 2, handler: () => handleDigitClick('0') }, // Zero spans 2 columns
{ id: 'decimal', label: '.', className: `${styles.button} ${styles.decimal}`, cols: 1, handler: handleDecimalClick },
];
return (
<div className={styles.calculator}>
<div className={styles.display}>{display}</div>
<div className={styles.buttons}>
{buttonLayout.map((btn) => {
// Define the style object for grid positioning
const style = {
gridColumn: `span ${btn.cols}`,
gridRow: `span ${btn.rows || 1}`, // Default to 1 row span
};
return (
<button
key={btn.id}
onClick={btn.handler}
className={btn.className} // Use pre-defined classNames
style={style} // Apply grid span styles
>
{btn.label}
</button>
);
})}
</div>
</div>
);
};
export default Calculator;
2. components/Calculator.module.css
3. pages/index.js
import Head from 'next/head';
import Calculator from '../components/Calculator'; // Import the Calculator component
import styles from '../styles/Home.module.css'; // Default Next.js home styles
export default function HomePage() {
return (
<div className={styles.container}>
<Head>
<title>Next.js Calculator</title>
<meta name="description" content="A simple calculator app built with Next.js" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
React Calculator in Next.js
</h1>
{/* Render the Calculator component */}
<Calculator />
</main>
</div>
);
}
4. styles/Home.module.css (Optional basic styling)
/* styles/Home.module.css */
.container {
min-height: 100vh;
padding: 0 0.5rem;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background-color: #f8f9fa; /* Light background */
}
.main {
padding: 5rem 0;
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.title {
font-size: 2.5rem; /* Responsive title size */
line-height: 1.15;
margin-bottom: 2rem;
color: #222;
text-align: center;
}
How to Run:
npx create-next-app my-calculator-appcd my-calculator-appcomponents/Calculator.js, components/Calculator.module.css, and optionally adjust pages/index.js and styles/Home.module.css).npm run dev or yarn devhttp://localhost:3000.You should see a functional calculator interface!
/* components/Calculator.module.css */
/* Calculator Container */
.calculator {
width: 320px; /* Standard calculator width */
margin: 50px auto; /* Center on page */
border: 1px solid #ccc;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.15);
background-color: #e0e0e0; /* Slightly darker background for contrast */
display: flex;
flex-direction: column;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
/* Display Screen */
.display {
background-color: #333; /* Dark display background */
color: #fff; /* White text */
font-size: 2.8em; /* Large font size */
padding: 20px 25px; /* Padding around text */
text-align: right;
min-height: 70px; /* Minimum height for display */
display: flex;
align-items: center;
justify-content: flex-end;
overflow-wrap: break-word; /* Wrap long numbers if necessary */
border-bottom: 1px solid #444; /* Subtle separator */
}
/* Button Grid Container */
.buttons {
display: grid;
/* Define 4 columns of equal fraction */
grid-template-columns: repeat(4, 1fr);
/* Define rows implicitly based on content or explicitly if needed */
gap: 1px; /* Small gap between buttons for visual separation */
padding: 5px; /* Padding around the grid */
background-color: #ccc; /* Background color for the gaps */
border-radius: 0 0 8px 8px; /* Match calculator corners */
}
/* Base Button Style */
.button {
font-size: 1.6em; /* Font size for button text */
font-weight: 500; /* Medium font weight */
border: none; /* Remove default border */
background-color: #fff; /* White button background */
color: #333; /* Dark text color */
cursor: pointer;
transition: background-color 0.2s ease-in-out, box-shadow 0.2s ease-in-out;
display: flex;
align-items: center;
justify-content: center;
box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.08); /* Subtle inner shadow for depth */
aspect-ratio: 1 / 1; /* Make buttons square by default */
padding: 10px; /* Padding inside buttons */
}
/* Button Hover Effect */
.button:hover {
background-color: #f0f0f0; /* Slightly darker hover */
}
/* Button Active (Pressed) Effect */
.button:active {
background-color: #e0e0e0; /* Even darker when pressed */
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.2); /* Pressed effect */
}
/* Special Button Styles */
/* Clear Button (AC) - Spans 2 columns */
.clear {
background-color: #f4574b; /* Reddish color */
color: white;
box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.15);
}
.clear:hover { background-color: #e04e43; }
.clear:active { background-color: #c9453d; }
/* Operator Buttons (+, -, *, /) */
.operator {
background-color: #fca457; /* Orangey color */
color: white;
box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.15);
}
.operator:hover { background-color: #e6934e; }
.operator:active { background-color: #cc8144; }
/* Equals Button (=) - Spans 2 rows */
.equals {
background-color: #7cdd7a; /* Greenish color */
color: white;
grid-row: span 2; /* Explicitly set row span */
box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.15);
}
.equals:hover { background-color: #6fca6d; }
.equals:active { background-color: #5eb95b; }
/* Zero Button (0) - Spans 2 columns */
.zero {
grid-column: span 2;
background-color: #f5f5f5; /* Lighter gray for number buttons */
box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.05);
}
.zero:hover { background-color: #e8e8e8; }
.zero:active { background-color: #dcdcdc; }
/* Decimal Button (.) */
.decimal {
background-color: #f5f5f5; /* Lighter gray */
box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.05);
}
.decimal:hover { background-color: #e8e8e8; }
.decimal:active { background-color: #dcdcdc; }
/* Ensure remaining number buttons inherit base style correctly */
.button:not(.clear):not(.operator):not(.equals):not(.zero):not(.decimal) {
background-color: #fff; /* Default white for digits */
box-shadow: inset 0 -3px 0 rgba(0, 0, 0, 0.08);
}
.button:not(.clear):not(.operator):not(.equals):not(.zero):not(.decimal):hover {
background-color: #f0f0f0;
}
.button:not(.clear):not(.operator):not(.equals):not(.zero):not(.decimal):active {
background-color: #e0e0e0;
}