DEV Community

adriangheo
adriangheo

Posted on

02.04 React State - basic counter with page title change (functional 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 "./App.css"

function App() {
  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, { useState, useEffect} from "react";

function Counter(){
    const [counter, handleClick] = useState(0);

    useEffect(() => {
      document.title = `You clicked ${counter} times`;
    });

    return (
        <div>
          <button onClick={() => ( handleClick(counter + 1)) }>Increment counter</button>
          {/* <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)