How to create a simple counter Using ReactJS?
React counter app is a program that allows users to interact with a numerical counter value. It demonstrates basic state management and user interaction within a user interface.
Prerequisites:
Approach:
To create a simple counter app in React:
- Create a useState variable named count and setCount() to update the state.
- Create buttons named increment and decrement that modify the count state +1 and -1 respectively.
- Link the buttons with setCount using event handlers.
We’ll be creating a simple application where we have 2 buttons one to increment and one to decrement.
Steps to Create React Application:
Step 1: Create a React application using the following command:
npx create-react-app counter
Step 2: After creating your project folder i.e. counter, move to it using the following command:
cd counter
Project Structure:
Project Structure
Example: This example demonstrate a simple counter app using useState hook, and the count increase and descrease on click.
Javascript
import React, { useState } from "react" ;
import "./App.css" ;
const App = () => {
const [counter, setCounter] = useState(0);
const handleClick1 = () => {
setCounter(counter + 1);
};
const handleClick2 = () => {
setCounter(counter - 1);
};
return (
<div
style={{
display: "flex" ,
flexDirection: "column" ,
alignItems: "center" ,
justifyContent: "center" ,
fontSize: "300%" ,
position: "absolute" ,
width: "100%" ,
height: "100%" ,
top: "-15%" ,
}}
>
Counter App
<div
style={{
fontSize: "120%" ,
position: "relative" ,
top: "10vh" ,
}}
>
{counter}
</div>
<div className= "buttons" >
<button
style={{
fontSize: "60%" ,
position: "relative" ,
top: "20vh" ,
marginRight: "5px" ,
backgroundColor: "green" ,
borderRadius: "8%" ,
color: "white" ,
}}
onClick={handleClick1}
>
Increment
</button>
<button
style={{
fontSize: "60%" ,
position: "relative" ,
top: "20vh" ,
marginLeft: "5px" ,
backgroundColor: "red" ,
borderRadius: "8%" ,
color: "white" ,
}}
onClick={handleClick2}
>
Decrement
</button>
</div>
</div>
);
};
export default App;
|
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: This output will be visible on the http://localhost:3000/ on the browser window.
Last Updated :
28 Nov, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...