-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReact-ManageStateLocally
More file actions
45 lines (42 loc) · 1.53 KB
/
React-ManageStateLocally
File metadata and controls
45 lines (42 loc) · 1.53 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class DisplayMessages extends React.Component {
constructor(props) {
super(props);
this.state = {
input: "",
messages: []
}
// !!REMEMBER TO BIND THIS TO METHODS OTHERWISE THEY WONT WORK!!(NOT DONE IN TIC TAC TOE GAME!!!) - SEE CODEPEN
this.handleChange = this.handleChange.bind(this);
this.submitMessages = this.submitMessages.bind(this);
}
// !!! be careful with "this.setState"
// the syntax is this.setState({property1:value, property2: value});
this.setState({
input: event.target.value,
});
}
submitMessages(){
// MAKE SHALLOW COPY OF ARRAY
let newMsg = this.state.messages.slice();
this.setState ({
// ADD THE CURRENT INPUT TO THE NEW COPIED ARRAY
messages : newMsg.concat(this.state.input),
input : "",
});
}
render() {
!!!!// CREATE CONSTANT(why would this be a constant and not a let) THAT IS AN ARRAY OF <li> ITEMS
//!! be careful that the variable being used in the map function is put between curly brackets between the <li> tags
// as this variable will be going into JSX in the render method and will not be read as a variable otherwise.
const messages = this.state.messages.map((message) => <li>{message}</li>);
return (
<div>
<h2>Type in a new Message:</h2>
<input onChange = {this.handleChange} value= {this.state.input}/>
<button onClick = {this.submitMessages} > Submit</button>
// RENDER THE variable/constant to the ul elements
<ul>{messages}</ul>
</div>
);
}
};