Create Counter App in React with Stateful Component | IndianTechnoEra
![]() |
| Create Counter App in React with Stateful Component | Indiantechnoera |
To create a counter app in react with stateful component follow the steps-
- Setup React environment with VSCode
- If already setup follow step 7 and 8
- Download and Install Node.JS
- Goto Link choose system and Download Node.Js
- Install downloaded Node.js and confirm in CMD with node --version
- Create a folder and open with VS-Code
- Goto terminal or click (Ctrl + Shift + ` )
- Run npx create-react-app myapp in terminal (it will take some time and create a project with myapp name Here 'myapp' is your project name)
- After successfully completed the downloading you will get some file and folders
- Goto src folder and delete all files of src folder
- Then right click on src folder and create three new file as the given name
- index.js
- MyCounter.js
- MyCounter.css
- Then copy all the code corresponding with name into the files and save
- Then goto terminal or (Ctrl + Shift + `)
- Run cd myapp in terminal
- Then run npm start in terminal
- Then localhost will create and a browser page will open and you will see the output
MyCounter.js
import React from 'react'
import './MyCounter.css'
class MyCounter extends React.Component {
constructor () {
super()
this.state = { count: 0 }
}
render () {
return (
<>
<div id='container'>
<h1>My Counter App</h1>
<div id='result'>Counting : {this.state.count}</div>
<button
onClick={event => {
const countUpdate = this.state.count + 1
this.setState({ count: countUpdate })
}}
>
Increment
</button>
<button
onClick={event => {
const countUpdate = this.state.count - 1
this.setState({ count: countUpdate })
}}
>
Decrement
</button>
</div>
</>
)
}
}
export default MyCounter;
index.js
import React, { Fragment } from 'react'
import ReactDOM from 'react-dom/client'
import MyCounter from './MyCounter'
const root = ReactDOM.createRoot(document.getElementById('root'))
root.render(
<>
<MyCounter />
</>
)
MyCounter.css
#result{
font-size: 55px;
padding: 10px;
margin-bottom: 10px;
}
#container{
border-top: 100px;
padding: 10px;
align-items: center;
text-align: center;
font-size: 35px;
}
button{
height: auto;
padding: 10px;
margin: 10px;
cursor: pointer;
font-size: 30px;
background-color: aqua;
border-radius: 10px;
}
button:hover{
background-color: blue;
color: white;
}
