DEV Community

adriangheo
adriangheo

Posted on

02.01 React State - basic counter (class components)

App preview:
The way the app will look like

Project files:
An image of project file structure


src/App.js

import Counter from './Counter'
import React from 'react';
import './App.css'

class App extends React.Component{
  render(){
    return (
      <div className="app">
        <Counter/>
      </div>
    );
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

src/App.css

.app{
    background-color: lightskyblue;
    padding: 20px 10px;
}
Enter fullscreen mode Exit fullscreen mode


src/Counter.jsx

import React from "react";

class Counter extends React.Component {
  state = {
    counter: 0
  };

  handleClick = () => {
    this.setState((prevState) => ({ counter: prevState.counter + 1 }));
  };

  render() {
    const { counter } = this.state;

    return (
      <div>
        <button onClick={this.handleClick}>Increment counter</button>
        <div>Counter value is {counter}</div>
      </div>
    );
  }
}

export default Counter
Enter fullscreen mode Exit fullscreen mode

Top comments (0)