Created
October 29, 2018 02:26
-
-
Save sambostock/a12c88d1dfe92a903cda6d06c0cbf168 to your computer and use it in GitHub Desktop.
Trivial React State Hook example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Component } from 'react' | |
export default ClassBasedToggle extends React.Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
on: false, | |
} | |
this.handleToggle = this.handleToggle.bind(this) | |
} | |
handleToggle() { | |
this.setState({ on: !this.state.on }) | |
} | |
render() { | |
return <button onClick={handleToggle}>Toggle {this.state.on ? 'off' : 'on'}</button> | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useState } from 'react' | |
export default function HookBasedToggle(props) { | |
const [on, setOn] = useState(false) | |
function handleToggle() { | |
setOn(!on) | |
} | |
return <button onClick={handleToggle}>Toggle {on ? 'off' : 'on'}</button> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment