What you'll build
A functional web calculator with React and TypeScript. It will have numeric buttons 0-9, basic operations (+, -, *, /), decimal handling, and a display showing the current operation. The design will mimic a real physical calculator. You'll learn to handle complex state, click events, and mathematical logic in an interactive interface.
Step 1: Ask an AI for the calculator
I need a web calculator with:
- Operations: +, -, *, /
- Numeric buttons 0-9
- Equals and clear button
- Display showing the operation
- Decimal handling
- React with TypeScript
- Tailwind CSS for styles
- Physical calculator design
Give me the complete code.
Key concepts
| Concept | Implementation |
|---|---|
| State | Current number, pending operation |
| Events | onClick on each button |
| Logic | Function that evaluates expression |
Typical code
const [display, setDisplay] = useState('0')
const [prevValue, setPrevValue] = useState<number | null>(null)
const [operator, setOperator] = useState<string | null>(null)
const handleNumber = (num: string) => {
setDisplay(display === '0' ? num : display + num)
}
const handleOperator = (op: string) => {
setPrevValue(parseFloat(display))
setOperator(op)
setDisplay('0')
}
const calculate = () => {
if (prevValue !== null && operator) {
const current = parseFloat(display)
let result: number
switch (operator) {
case '+': result = prevValue + current; break
case '-': result = prevValue - current; break
case '*': result = prevValue * current; break
case '/': result = prevValue / current; break
default: return
}
setDisplay(String(result))
}
}
Possible improvements
- Operation history
- Scientific functions (%, โ)
- Numeric keyboard
- Dark mode
Next step
โ Interactive Quiz โ Game logic