DEV Community

adriangheo
adriangheo

Posted on

02.03 React State - basic counter with page title change (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 = {
        count: 0
    }

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

    componentDidUpdate(prevProps, prevState){
        if(prevState.count !== this.state.count){
            document.title = `You clicked ${this.state.count} times`;
        }
    }

    render(){
        return(
            <div>
                <button onClick={()=>{this.handleClick()}}>Push me</button>
                <div>nr: {this.state.count}</div>
            </div>
        )
    }
}

export default Counter
Enter fullscreen mode Exit fullscreen mode

Top comments (0)