![]() |
| Counter App in React with Stateful Component | IndianTechnoEra |
Aim:
Create a simple Counter App in React with stateful Component.
Component 1: Main App Part
| MyCouter.js |
|---|
import React from 'react' import './MyCounter.css' var title = document.title='CounterApp | Stateful' class MyCounter extends React.Component { constructor () { super() this.state = { count: 0} } render () { return ( <> <div id='container'> <div id='container-box'> <div id='app-title'> <h1>{title}</h1> <div id='result'> <h1>You clicked {this.state.count} time (s)</h1> </div> <div id='bottom'></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> <br></br> <div /> </div> </div> </div> </> ) } } export default MyCounter; |
Component 1: CSS Part
| MyCounter.css |
|---|
body{background-color:#000;color:#fff} #container{justify-content:center;align-items:center;text-align:center;font-size:35px;height:100%;width:100%;display:flex;flex-direction:column;position:absolute} #container-box{background-color:#7fffd4;padding:20px;display:block;border:2px solid #000;border-radius:20px;color:#000} #result{font-size:55px;padding:10px;margin-bottom:10px;box-sizing:border-box;background-color:#8804df;border:2px dotted #000;color:#fff} button{height:auto;padding:10px;margin:10px;cursor:pointer;font-size:30px;background-color:aqua;border-radius:10px;justify-content:space-around} button:hover{background-color:blue;color:#fff} button:active{background-color:red} |
Component 1: Index Part
| index.js |
|---|
import ReactDOM from 'react-dom/client' import React from 'react' import MyCounter from './MyCounter' const root = ReactDOM.createRoot(document.getElementById('root')) root.render( <> <React.StrictMode> <MyCounter /> </React.StrictMode> </> ) |
