Skip to content

Instantly share code, notes, and snippets.

@jtorreggiani
Created March 2, 2019 00:44
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save jtorreggiani/8120b8775174179e2885740faea316c2 to your computer and use it in GitHub Desktop.
Basic todos page
import React, { Component } from 'react'
const todosUrl = 'http://localhost:3001/todos'
function Todo ({ number, todo }) {
return (
<li>{number}. { todo.title }</li>
)
}
class Todos extends Component {
state = { title: '', todos: [] }
componentDidMount () {
fetch(todosUrl)
.then(response => response.json())
.then(todos => this.setState({ todos }))
}
onChange = ({ target }) => {
this.setState({ title: target.value })
}
addTodo = () => {
const { todos, title } = this.state
const options = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ title })
}
fetch(todosUrl, options)
.then(response => response.json())
.then(todo => this.setState({ todos: [...todos, todo], title: '' }))
}
render () {
return (
<div>
<h1>Todos</h1>
<input
type="text"
onChange={this.onChange}
value={this.state.title}
/>
<button onClick={this.addTodo}>Add Todo</button>
<ul className="App-todo-list">
{ this.state.todos.map((todo, index) =>
<Todo key={index} number={index + 1} todo={todo} />
)}
</ul>
</div>
)
}
}
export default Todos
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment