Creating A Simple Calculator With React

A calculator is one of the clearest ways to learn React because its interface is familiar while its behaviour exposes the essentials of interactive development. A display, number pad, operators and an equals button create a small application with visible state changes, event handling and conditional rendering.

The project can remain deliberately small, yet still reflect professional habits. A useful calculator should handle decimals, repeated operations, clearing, negative values and division by zero without confusing the person using it. These details turn a basic coding exercise into a practical front-end component.

For an Australian audience, the interface can use familiar conventions such as the dollar sign when demonstrating currency calculations, a responsive layout suited to mobile screens in Sydney or Perth, and clear text that remains readable in bright outdoor conditions. The underlying arithmetic should stay precise rather than applying cash-rounding rules automatically.

A restrained visual direction can help the project feel polished. The nature-inspired spacing, photography and typography shown on this visual reference suggest how colour, whitespace and hierarchy can make a simple interface easier to understand without adding unnecessary decoration.

Set Up The React Project

Start with a modern React project created through Vite. In a terminal, run npm create vite@latest react-calculator -- --template react, move into the new directory, install the dependencies and launch the development server. Vite gives the application a quick feedback loop, which is especially useful when adjusting button states and responsive styles.

The entry point usually renders an App component into the page. Keep the initial structure uncomplicated: App can hold the calculator state, while smaller components such as Display, Keypad and Button handle presentation. This division makes each part easier to test and gives the interface a clear component tree.

A sensible folder structure might include src/components, src/App.jsx and src/App.css. Avoid creating a separate file for every minor visual element at the beginning. The goal is to make the data flow easy to follow, then extract components when repeated markup or growing logic starts to reduce clarity.

Model The Calculator State

A calculator needs to remember the number currently shown, the previous number, the selected operation and whether the next digit should begin a fresh value. In React, these values can be managed with useState. A simple model might use display, storedValue, operator and waitingForOperand.

When a user presses a number, append it to the display unless the calculator is waiting for a new operand. The decimal key needs a guard so that one value cannot contain two decimal points. A leading zero can be replaced when the first meaningful digit is entered, preventing displays such as 0007.

Operations should be handled through a small set of functions rather than scattered conditions inside the JSX. A calculate function can receive two numbers and an operator, then return addition, subtraction, multiplication or division. Storing numeric values as numbers while displaying them as strings gives the interface flexibility without making arithmetic logic difficult to inspect.

For a currency example, use Australian dollars in the visible labels or sample calculations, but do not assume every calculation is monetary. A result such as $24.50 may be useful in a budgeting demonstration, while a general calculator should avoid automatically adding a dollar sign to ordinary numbers.

Build The Keypad And Display

The display should show the current value prominently and provide enough contrast for quick scanning. A secondary line can show the previous operand and operator, such as 120 +, while the main line shows the number being entered. Use a live region carefully if announcing changes to assistive technology, since announcing every keystroke can become distracting.

The keypad can be generated from an array of button definitions. Each definition may contain a label, a type and a value, allowing React to render number keys, operators, clear, backspace, decimal and equals controls consistently. Assign stable keys and attach one click handler that interprets the button type.

CSS Grid is well suited to the layout. A four-column grid gives operators a consistent position and allows the zero key to span two columns if desired. Use flexible sizing such as minmax(0, 1fr) so the calculator remains comfortable on a small Android phone, an iPhone used on a Melbourne tram, or a desktop monitor.

Use button elements rather than clickable div elements. Native buttons provide keyboard behaviour, focus handling and semantic meaning by default. Add visible :focus-visible styling, adequate touch targets and colour contrast. These choices support the expectations of the Australian Disability Discrimination Act 1992 and make the interface more usable for everyone.

Handle Operations And Edge Cases

The equals action should calculate only when both a stored value and an operator exist. After producing a result, replace the displayed value, clear the pending operator and mark the calculator as ready for a new operand. If the user enters another operator immediately, the new operator can be stored while keeping the current result available.

Division by zero requires a deliberate response. Instead of allowing Infinity or an unusable error to appear, display a short message such as Error, then let the clear button restore normal operation. Similar protection is useful for invalid input, unexpectedly long numbers and results that exceed the display width.

A backspace control can remove the last character, while clear resets every state value. A plus-minus button can convert the current display to a negative number, provided the value is not zero or an error message. Keyboard support for digits, operators, Enter, Escape and Backspace can make the calculator faster for desktop users.

JavaScript floating-point arithmetic can produce results such as 0.1 + 0.2 = 0.30000000000000004. For a learning project, format results to a reasonable number of decimal places before displaying them. If the calculator later supports financial workflows, use a decimal arithmetic library or represent cents as integers rather than relying on binary floating-point values.

Improve The Experience For Australian Users

A calculator used in Australia may support practical situations such as splitting a restaurant bill in Brisbane, checking a weekly grocery total in Adelaide or comparing travel costs between Sydney and Canberra. A dedicated percentage key can help with discounts, tips and GST examples, although the calculation rules should be clearly documented so users understand what the result represents.

GST is generally 10 per cent in Australia, but a general calculator should not silently add or remove it. If a GST mode is added, label whether the entered amount is before or after tax. This avoids confusion between adding 10 per cent to a price and extracting the GST component from a GST-inclusive price.

Time and date examples also need local awareness. Australia spans several time zones, and daylight saving changes affect places such as Melbourne, Sydney and Hobart while Queensland follows a different arrangement. A calculator that later expands into scheduling or billing should never assume that one local time applies nationwide.

A clean domain and page structure also contribute to discoverability when the project is published. Background reading about domain and SEO can help explain why a memorable address, descriptive page title and stable URL matter. Search visibility should support the tool, not distract from its fast, focused interface.

Test And Publish The Calculator

Test the logic independently from the visual layout. Check ordinary sequences such as 7 + 5 =, chained operations such as 10 × 3 − 4, decimal input, negative numbers, repeated equals presses and clearing after an error. Also test pressing an operator before entering a number and entering several decimal points.

React Testing Library can simulate user actions through accessible button names. A test should verify what a person sees rather than relying on internal state variables. For example, click buttons labelled 8, ÷, 2 and =, then assert that the display contains 4. This approach keeps tests useful even if the component structure changes.

Before deployment, run the production build and inspect the result on narrow and wide screens. Check that text does not overflow, buttons remain large enough to tap and keyboard focus is obvious. Test in current versions of Chrome, Safari and Firefox, including a phone connected through a typical mobile network rather than assuming a fast office connection.

Practical Checks Before Release

A static build can be deployed to services such as Netlify, Vercel or GitHub Pages. Keep the application free of unnecessary personal data, analytics and tracking unless there is a clear reason to collect them. If data collection is introduced later, review Australian Privacy Act obligations and explain the purpose in an accessible privacy notice.

A small React calculator demonstrates a complete development cycle: planning state, composing components, managing events, designing for touch and keyboard use, testing edge cases and publishing a responsive interface. Its modest size makes every decision visible, which is why it remains such a useful project for learning modern front-end development.

Contact