This tutorial guides you through building a React calculator app. You'll learn wireframing, layout design, component creation, state updates, and output formatting. A deployed project link and source code are provided for reference.
Key Concepts Covered:
- Wireframing and Design: Start with a basic wireframe (using Figma or similar) to define component structure before styling.
-
Project Setup: Use
npx create-react-app
for quick project initialization, then clean up the default files. -
Component Organization: Structure the app with components:
Wrapper
,Screen
,ButtonBox
, andButton
, each with its CSS. - State Management: Use React state and handlers for calculations ( , -, *, /), reset, and value inversion.
- Input/Output Formatting: Format numbers with separators and handle multiple decimal points.
- Component Interaction: Ensure seamless interaction between components for a functional app.
Planning and Design:
The calculator will include:
- Basic arithmetic operations ( , -, *, /)
- Decimal support
- Percentage calculation
- Value inversion ( /-)
- Reset functionality
- Number formatting for large numbers
- Dynamic output resizing
A wireframe is essential for planning the layout and identifying components. Color schemes are less important at this stage.
A visually appealing color scheme is crucial:
- Wrapper should contrast with the background.
- Screen and button values should be easily readable.
- The equals button should have an accent color.
Project Setup and Component Creation:
Create the React project:
npx create-react-app calculator cd calculator
Clean up the src
folder, keeping only App.js
, index.css
, and index.js
. Create a components
folder within src
and the necessary files for each component (Wrapper.js
, Wrapper.css
, etc.).
Component Implementation (Examples):
- Wrapper.js: A container for the calculator, providing centering and styling.
-
Screen.js: Displays the calculated values, using
react-textfit
for dynamic resizing. - ButtonBox.js: A container for the buttons.
-
Button.js: Individual calculator buttons with
onClick
handlers.
(Note: The full code for each component and handler function is lengthy and omitted here for brevity. Refer to the original input for complete code.)
Functionality and State Management:
Use useState
to manage the calculator's state (num
, sign
, res
). Implement handler functions (numClickHandler
, signClickHandler
, equalsClickHandler
, etc.) to update the state based on button clicks. The equalsClickHandler
performs the actual calculations.
Input Formatting:
Use the provided toLocaleString
and removeSpaces
functions to format numbers with thousands separators and handle spaces appropriately.
Testing and Deployment:
Thorough testing is crucial. Deployment can be done using platforms like Netlify, Vercel, or GitHub Pages.
FAQs (Summary):
The FAQs section covers setting up the project, key components, handling user input and calculations, error handling, styling, testing, deployment, adding features, and using external libraries. Refer to the original input for detailed answers.
Remember to consult the original input for the complete code and detailed explanations of each function. This response provides a streamlined overview of the tutorial.
The above is the detailed content of React Tutorial: Build a Calculator App from Scratch. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

ArtGPT
AI image generator for creative art from text prompts.

Stock Market GPT
AI powered investment research for smarter decisions

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



This article aims to solve the problem of deep URL refresh or direct access causing page resource loading failure when deploying single page applications (SPAs) on Vercel. The core is to understand the difference between Vercel's routing rewriting mechanism and browser parsing relative paths. By configuring vercel.json to redirect all paths to index.html, and correct the reference method of static resources in HTML, change the relative path to absolute path, ensuring that the application can correctly load all resources under any URL.

This tutorial aims to solve the problem of loading assets (CSS, JS, images, etc.) when accessing multi-level URLs (such as /projects/home) when deploying single page applications (SPAs) on Vercel. The core lies in understanding the difference between Vercel's routing rewriting mechanism and relative/absolute paths in HTML. By correctly configuring vercel.json, ensure that all non-file requests are redirected to index.html and correcting asset references in HTML as absolute paths, thereby achieving stable operation of SPA at any depth URL.

Qwikachievesinstantloadingbydefaultthroughresumability,nothydration:1)TheserverrendersHTMLwithserializedstateandpre-mappedeventlisteners;2)Norehydrationisneeded,enablingimmediateinteractivity;3)JavaScriptloadson-demand,onlywhenuserinteractionoccurs;4

In JavaScript, the most common method to add elements to the beginning of an array is to use the unshift() method; 1. Using unshift() will directly modify the original array, you can add one or more elements to return the new length of the added array; 2. If you do not want to modify the original array, it is recommended to use the extension operator (such as [newElement,...arr]) to create a new array; 3. You can also use the concat() method to combine the new element array with the original number, return the new array without changing the original array; in summary, use unshift() when modifying the original array, and recommend the extension operator when keeping the original array unchanged.

Usetheloading="lazy"attributefornativelazyloadinginmodernbrowserswithoutJavaScript.2.Formorecontrolorolderbrowsersupport,implementlazyloadingwiththeIntersectionObserverAPIbysettingdata-srcfortheactualimageURLandusingaplaceholderinsrc.3.Obse

ToaccessandmodifyHTMLelementsusingJavaScript,firstselecttheelementusingmethodslikedocument.getElementById,document.querySelector,ordocument.querySelectorAll,thenalteritscontent,attributes,orstyles;forexample,useelement.textContentforsafetextupdates,e

This article explores in-depth security vulnerabilities in custom JavaScript XSS defense functions, especially incomplete character escape and easy bypass to keyword-based filtering. By analyzing an example function, it reveals the risks of unprocessed keyword characters such as quotes and backquotes, and how code obfuscation techniques circumvent simple keyword detection. The article emphasizes the importance of context-sensitive escape and recommends the adoption of mature libraries and multi-layer defense strategies to build more robust security protection.

This article aims to solve the problem of redirecting the external link redirect button in jQuery pop-up window causing jump errors. When a user clicks multiple external links in succession, the jump button in the pop-up may always point to the first clicked link. The core solution is to use the off('click') method to undo the old event handler before each binding of a new event, ensuring that the jump behavior always points to the latest target URL, thus achieving accurate and controllable link redirection.
