Files
Randell Dawson 1494a50123 fix(guide): restructure curriculum guide articles (#36501)
* fix: restructure certifications guide articles
* fix: added 3 dashes line before prob expl
* fix: added 3 dashes line before hints
* fix: added 3 dashes line before solutions
2019-07-24 13:29:27 +05:30

78 lines
1.7 KiB
Markdown

---
title: Manage State Locally First
---
# Manage State Locally First
---
## Hints
### Hint 1
Bind the method calls in component attributes with ```this```, e.g.
```jsx
<input onChange={this.handleChange.bind(this)} value={this.state.input}/>
```
or the binding can be done beforehand
### Hint 2
Pass ```event``` to ```handleChange()``` method declaration and note that ```event.target.value``` stores the input value.
### Hint 3
You may wanna add the following ```<div>``` into render content to check if the ```handleChange()``` method is working.
```jsx
<div>{this.state.input}</div>
```
### Hint 4
spread operator ```...``` can be used for array concatenation in ```submitMessage()``` method declaration.
---
## Solutions
<details><summary>Solution 1 (Click to Show/Hide)</summary>
```jsx
class DisplayMessages extends React.Component {
constructor(props) {
super(props);
this.state = {
input: '',
messages: []
}
}
// add handleChange() and submitMessage() methods here
handleChange(event){
this.setState({
input: event.target.value,
messages: this.state.messages
})
}
submitMessage(){
this.setState({
input: '',
messages: [...this.state.messages, this.state.input]
})
}
render() {
return (
<div>
<h2>Type in a new Message:</h2>
{ /* render an input, button, and ul here */ }
<input onChange={this.handleChange.bind(this)} value={this.state.input}/>
<button onClick={this.submitMessage.bind(this)}>Submit</button>
<ul>
{this.state.messages.map((x, i)=>{
return <li key={i}>{x}</li>
})}
</ul>
{ /* change code above this line */ }
</div>
);
}
};
```
</details>