Skip to content

Instantly share code, notes, and snippets.

@JoelCodes
Created June 7, 2019 15:19
Show Gist options
  • Save JoelCodes/36c74ff1865313be10c287c859ce88e3 to your computer and use it in GitHub Desktop.
Save JoelCodes/36c74ff1865313be10c287c859ce88e3 to your computer and use it in GitHub Desktop.
Incrementer Hook Example
import React, {Component} from 'react';
import {render} from 'react-dom';
// class IncrementContainer extends Component {
// constructor(props){
// super(props);
// this.state = {count: 0};
// this.increment = this.increment.bind(this);
// }
// increment(){
// this.setState(({count}) => ({count: count + 1}))
// }
// render(){
// return <IncrementPresenter count={this.state.count} increment={this.increment}/>
// }
// }
function useIncrementer(){
const [count, setCount] = React.useState(9001);
function increment(){
setCount((count) => count + 1);
}
return {
count, increment
}
}
function IncrementContainer(){
// const [count, setCount] = React.useState(9001);
// function increment(){
// setCount((count) => count + 1);
// }
// const {count, increment} = useIncrementer();
// return <IncrementPresenter count={count} increment={increment}/>
return <IncrementPresenter {...useIncrementer()}/>
}
function IncrementPresenter({count, increment}){
return (<div>
<p>
<button onClick={increment}>The Button</button>
</p>
<p>The Button has been pressed {count} times</p>
</div>);
}
const root = document.getElementById('react-root');
render(<IncrementContainer/>, root);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Incrementer</title>
<link href="https://fonts.googleapis.com/css?family=Raleway&display=swap" rel="stylesheet">
<style>
* {
font-family: 'Raleway', sans-serif;
font-size: 40px;
}
</style>
</head>
<body>
<div id="react-root"></div>
<script src="./app.jsx"></script>
</body>
</html>
{
"name": "incrementer",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "parcel index.html app.jsx"
},
"keywords": [],
"author": "Joel Shinness <[email protected]> (http://joelshinness.com)",
"license": "ISC",
"dependencies": {
"parcel-bundler": "^1.12.3",
"react": "^16.8.6",
"react-dom": "^16.8.6"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment