Skip to content

Instantly share code, notes, and snippets.

@Nitemaeric
Last active January 2, 2019 08:28
Show Gist options
  • Save Nitemaeric/ab02b01d4d9b0b108310ec780536939f to your computer and use it in GitHub Desktop.
Save Nitemaeric/ab02b01d4d9b0b108310ec780536939f to your computer and use it in GitHub Desktop.
React TodoApp Example
import React from 'react'
import TodoList from './TodoList'
class TodoApp extends React.Component {
constructor (props) {
super(props)
this.state = {
items: [],
text: ''
}
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange (e) {
this.setState({ text: e.target.value })
}
handleSubmit (e) {
e.preventDefault()
if (this.state.text.length <= 0) {
return
}
const newItem = {
id: Date.now(),
text: this.state.text
}
this.setState(state => ({
items: state.items.concat(newItem),
text: ''
}))
}
render () {
return (
<div>
<h3>TODO</h3>
<TodoList items={this.state.items} />
<form onSubmit={this.handleSubmit}>
<label htmlFor="new-todo">
What needs to be done?
</label>
<input
id="new-todo"
onChange={this.handleChange}
value={this.state.text}
/>
<button>
Add #{this.state.items.length + 1}
</button>
</form>
</div>
)
}
}
import React from 'react'
class TodoList extends React.Component {
render () {
return (
<ul>
{
this.props.items.map(item => (
<li key={item.id}>{item.text}</li>
))
}
</ul>
)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment