1 - Simple Counter App
Description
Develop a React application that displays a counter with two buttons: one labeled "Increment" and one labeled "Decrement." Clicking the "Increment" button should increase the counter's value by 1, while clicking the "Decrement" button should decrease it by 1. The current counter value should be displayed clearly on the screen.
Algorithm
State Management: Utilize React's
useState
hook to manage the counter value as a state variable. Initialize the state with an initial value (e.g., 0).Button Functionalities: Define separate functions for handling click events on the "Increment" and "Decrement" buttons. Each function should update the counter state by 1 (increment) or -1 (decrement) using the
setState
method.Counter Display: Render the current counter value, retrieved from the state variable, within a dedicated UI element such as a
<span>
or a<p>
tag.
Code
CounterApp.ts
Explanation
useState Hook:
useState
creates a state variablecount
with an initial value of 0 and a setter functionsetCount
to update its value.Button Functions:
handleIncrement
andhandleDecrement
react to button clicks, adding or subtracting 1 from thecount
state, respectively.Counter Display: The current
count
value is displayed within a<span>
with the class "counter-value."UI Components: Classes like "counter-app" and "counter-value" provide basic styling for the components.
Additional Notes
This code implementation serves as a basic example. You can extend it further by adding features like:
Setting custom initial counter values.
Implementing minimum and maximum limits for the counter.
Adding visual effects upon increment or decrement.
Last updated