Last active
August 2, 2021 23:09
-
-
Save EduardoPazz/9dd83ffc75c0d553a3b3b0fdcb776027 to your computer and use it in GitHub Desktop.
React's setState 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
/* | |
It creates a button that when it's pressed, it creates another button with the counter incremented. The new button causes | |
the same action. Any clicked button will create a new button with the same behavior of the previous. | |
*/ | |
import React from 'react'; | |
import ReactDOM from 'react-dom'; | |
class Multiplier extends React.Component { | |
constructor(props) { | |
/* | |
Everytime we create a React's component as a class and want to use a constructor, IT MUST RECEIVE 'props' as | |
arguments and call super's constructor passing that 'props' as parameter. | |
*/ | |
super(props); | |
/*This line below is needed because JS is weird and causes 'this' keyword to be undefined | |
if the method is used outside the context of its class. In this case, the method 'Multiplier.handleClick' | |
is passed to the React to be called when this component is rendered.*/ | |
this.handleClick = this.handleClick.bind(this); | |
} | |
handleClick() { | |
/* | |
setState receives a anonymous function that returns what should be inside 'this.state'. In this case, it's | |
a object containing 'counter' and 'group' attributes. This is how React handle components' changes. | |
Look, we are calling the 'setState' of the 'parent' prop of a 'Multiplier' component. It's not 'Multiplier''s | |
setState. The 'parent' prop of 'Multiplier' is a reference/pointer to the 'ButtonsGroup' component. | |
i.e., When we click any of the buttons, its 'handleClick' method is called. This method executes a 'setState' | |
of the 'ButtonsGroup' component, which any of the 'Multiplier' button has a reference to | |
stored in its 'props.parent'. | |
*/ | |
this.props.parent.setState(previousState => ({ | |
counter: previousState.counter + 1, | |
group: previousState.group.concat([<Multiplier mId={previousState.counter + 1} parent={this.props.parent}/>]) | |
})); | |
} | |
render() { | |
return ( | |
<button onClick={this.handleClick}>{this.props.mId}</button> | |
); | |
} | |
} | |
class ButtonsGroup extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
counter: 0, | |
group: [<Multiplier mId={0} parent={this}/>] | |
}; | |
} | |
render() { | |
return ( | |
<div> | |
{this.state.group.map(m => m)} | |
</div> | |
); | |
} | |
} | |
function App(props) { | |
return ( | |
<main> | |
<ButtonsGroup /> | |
</main> | |
); | |
} | |
ReactDOM.render( | |
<App />, | |
document.getElementById('root') | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment