Skip to content

Instantly share code, notes, and snippets.

@MorenoMdz
Last active April 28, 2018 21:00
Show Gist options
  • Save MorenoMdz/01b8c1f78ec531f6c9fd039415efd9be to your computer and use it in GitHub Desktop.
Save MorenoMdz/01b8c1f78ec531f6c9fd039415efd9be to your computer and use it in GitHub Desktop.
/* setState always calls render again and it is async */
/* Calling UPPERCASE onClick with React */
class ClickExample extends Component {
constructor(props) {
super(props);
this.state = { name: "tim" };
}
render() {
return (
<div>
<p>{this.state.name}</p>
<button
type="button"
onClick={() => this.setState({ name: "TIM" })}
/>{" "}
UPPERCASE
</div>
);
}
}
/**
* The class has one state, name with value 'tim',
* The p tag displays the state.name value,
* When the button is clicked it will run the setState() callback, The onClick event will run
* that will replace the string value to 'TIM'
* When the setState is run later on, it will call render() again and it will remount the component
*/
/* With the method inside the class */
class ClickExample2 extends Component {
constructor(props) {
super(props);
this.state = { name: "tim" };
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
this.setState((prevState, props) => ({
name: prevState.name.toUpperCase()
}));
}
render() {
return (
<div>
<p>{this.state.name}</p>
<button type="button" onClick={this.handleClick} />
UPPERCASE
</div>
);
}
}
/**
* The class has a method that receives an event (the click), that will setState as callback
* and replace the name toUppeCase
* The class constructor will set bind the instance of thisHandleClick to itself
* as it loses scope when called async
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment