Skip to content

Instantly share code, notes, and snippets.

@EduardoPazz
Last active August 2, 2021 23:09
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 EduardoPazz/9dd83ffc75c0d553a3b3b0fdcb776027 to your computer and use it in GitHub Desktop.
Save EduardoPazz/9dd83ffc75c0d553a3b3b0fdcb776027 to your computer and use it in GitHub Desktop.
React's setState example
/*
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