React Counter Example App

JS
S
JavaScript

Using react function components. Example based on Flavio Copes tutorial.

1// =================== button.js  ===================
2import React from 'react';
3const Button =  ({ increment, onClickFunction }) => {
4  const handleClick = () => {
5    onClickFunction(increment);
6  }
7  return <button onClick={handleClick}>+{increment}</button>
8}
9export default Button;
10
11
12// =================== app.js  ===================
13import React, { useState } from 'react';
14import Header from './header';
15import Button from './button'
16import ReactDOM from 'react-dom';
17import logo from './logo.svg';
18import './styles.css';
19
20function App() {
21  // State via React Hooks
22  // initializes the count variable at 0 and provides us the setCount() method to update its value.
23  const [count, setCount] = useState(0);
24
25  const incrementCount = increment => {
26    console.log('incrementCount called', increment)
27    setCount(count + increment);
28  }
29
30  const handleResetClick = () => {
31    setCount(0);
32  }
33
34  return (
35    <div className="App">
36      <Header> </Header>
37      <Button onClickFunction={incrementCount} increment={1}/>
38      <Button onClickFunction={incrementCount} increment={10}/>
39      <button onClick={handleResetClick}>Reset Count</button>
40      <span> {count} </span>
41    </div>
42  );
43}
44
45export default App;
46

Created on 2/11/2019