Skip to content

Instantly share code, notes, and snippets.

@phungrk
Last active November 14, 2019 03:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phungrk/3eee94cc1f9dfde692a80d14ed1612b4 to your computer and use it in GitHub Desktop.
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
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