Core React Concepts for Calculator App
Necessary Concepts for Calculator App
Components
React components are the building blocks of a React app. A component is a reusable piece of UI, defined as a function (or class). For our calculator, we will create several components: for example, a Display component (to show the output) and a Button component (for each calculator button). Components use props (properties) to receive data.
In this app, the Button component will receive a prop like value="7" and an onClick handler function. Components use JSX syntax which looks like HTML.
For example, <Button value="1" onClick={handleClick} /> creates a button with label “1” and click logic. Breaking the UI into components (Display, Button, etc.) makes code more organized and reusable.
State and Props
React’s state allows components to remember information. In a functional component, we use the useState hook to create state variables. For instance, we might have const [display, setDisplay] = useState("0") in the App component to keep track of what is shown on the calculator screen.
When a button is clicked, we update this state (e.g., setDisplay(newValue)) and React automatically re-renders the display. Props are read-only inputs to components. For example, our Display component might get a value={display} prop, meaning it shows the current display state.
Props let child components (like Button) communicate back to the parent via callbacks (e.g., passing an onClick function as a prop). Understanding state and props is crucial: state changes trigger UI updates, and props pass data and event handlers down to children.
Functions and Event Handling
React components handle user actions with event handlers (functions). For our calculator, clicking a button triggers an event handler (e.g. onClick). We will write functions like handleClick(value) in the main component that decide what to do based on the value of the button clicked.
For instance, handleClick("5") appends “5” to the display state. We might also write separate functions for special keys (like handleClear() for AC, or handleEquals() for =). These functions use JavaScript logic to update state: performing arithmetic, resetting values, or converting to a percentage.
By handling events with functions, React lets us keep UI and logic tightly connected: when state updates in the function, the component re-renders with the new output.


