Created
October 16, 2019 16:56
-
-
Save polyrand/f1bafb4f97fde5f3a4cd934611ae1a0c to your computer and use it in GitHub Desktop.
Using hooks to set and update dicts as state in a react function.
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 React, { useState } from "react"; | |
import ReactDOM from "react-dom"; | |
class ClassExample extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { count: 0 }; | |
} | |
render() { | |
return ( | |
<div> | |
<p>You clicked {this.state.count} times</p> | |
<button onClick={() => this.setState({ count: this.state.count + 1 })}> | |
Click me! | |
</button> | |
</div> | |
); | |
} | |
} | |
function Example(props) { | |
const [count, setCount] = useState(0); | |
const [arrst, setArr] = useState({ count: 4 }); | |
return ( | |
<div> | |
<p>You clicked {count} times</p> | |
<button onClick={() => setCount(count + 1)}>Click me!</button> | |
<p>You clicked (arr) {arrst.count} times</p> | |
<button | |
onClick={() => { | |
const newObj = { count: arrst.count + 1 }; | |
setArr(newObj); | |
}} | |
> | |
Click me dict! | |
</button> | |
</div> | |
); | |
} | |
function App() { | |
return ( | |
<div> | |
<h1>test!</h1> | |
<ClassExample /> | |
<Example /> | |
</div> | |
); | |
} | |
ReactDOM.render(<App />, document.getElementById("root")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment