-
-
Save phungrk/3eee94cc1f9dfde692a80d14ed1612b4 to your computer and use it in GitHub Desktop.
React Practice - Imperative vs Declarative way go with Data down and action up concept
This file contains hidden or 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 from "react"; | |
import ReactDOM from "react-dom"; | |
// | |
const PersonOne = () => { | |
const [feeling, setFeeling] = React.useState("normal"); | |
const handleOnChangeFeeling = feeling => { | |
setFeeling(feeling); | |
}; | |
return ( | |
<div> | |
<p> | |
PersonOne: I'm <span>{feeling}</span> | |
</p> | |
<p>Don't</p> | |
<p>PersonTwo: I will change your feeling:</p> | |
<PersonTwoWrong setFeeling={setFeeling} /> | |
<p>Do:</p> | |
<p>PersonTwo: This is what I want to change your feeling:</p> | |
<PersonTwoRight onChangeFeeling={handleOnChangeFeeling} /> | |
</div> | |
); | |
}; | |
// Don't | |
const PersonTwoWrong = props => { | |
return ( | |
<div> | |
<button | |
onClick={() => props.setFeeling("Happy")} | |
style={{ background: "green" }} | |
> | |
Happy | |
</button> | |
<button | |
onClick={() => props.setFeeling("Angry")} | |
style={{ background: "red" }} | |
> | |
Angry | |
</button> | |
<button | |
onClick={() => props.setFeeling("Sad")} | |
style={{ background: "grey" }} | |
> | |
Sad | |
</button> | |
</div> | |
); | |
}; | |
// Good | |
const PersonTwoRight = props => { | |
return ( | |
<div> | |
<button | |
onClick={() => props.onChangeFeeling("Happy")} | |
style={{ background: "green" }} | |
> | |
Happy | |
</button> | |
<button | |
onClick={() => props.onChangeFeeling("Angry")} | |
style={{ background: "red" }} | |
> | |
Angry | |
</button> | |
<button | |
onClick={() => props.onChangeFeeling("Sad")} | |
style={{ background: "grey" }} | |
> | |
Sad | |
</button> | |
</div> | |
); | |
}; | |
// | |
function App() { | |
return ( | |
<div className="App"> | |
<h1>Keep the state above the widgets that use it</h1> | |
<PersonOne /> | |
</div> | |
); | |
} | |
// | |
const rootElement = document.getElementById("root"); | |
// | |
ReactDOM.render(<App />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment