Skip to content

Instantly share code, notes, and snippets.

@chris-burgin
Created January 31, 2018 18:38
Show Gist options
  • Save chris-burgin/4ae8199be54963b927b4aaa7adbc154b to your computer and use it in GitHub Desktop.
Save chris-burgin/4ae8199be54963b927b4aaa7adbc154b to your computer and use it in GitHub Desktop.
A component that stores an exact history of what you type.
import React, { Component } from "react"
export default class App extends Component {
constructor() {
super()
this.state = { messages: [] }
// binds
this._getLastMessage = this._getLastMessage.bind(this)
this._onMessageChange = this._onMessageChange.bind(this)
}
_getLastMessage() {
const lastMessage = this.state.messages[this.state.messages.length - 1]
return lastMessage === undefined ? "" : lastMessage
}
_onMessageChange(event) {
const messages = [...this.state.messages]
messages.push(event.target.value)
this.setState({ messages })
}
render() {
return (
<div className="App">
<input
type="text"
value={this._getLastMessage()}
onChange={this._onMessageChange}
style={{ margin: "10px" }}
/>
<MessageList messages={this.state.messages} />
</div>
)
}
}
class MessageList extends Component {
render() {
return (
<ul>
{this.props.messages.map((m, i) => <Message key={i} message={m} />)}
</ul>
)
}
}
class Message extends Component {
render() {
return <li style={{ margin: "10px" }}> {this.props.message} </li>
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment