Created
March 2, 2019 00:44
-
-
Save jtorreggiani/8120b8775174179e2885740faea316c2 to your computer and use it in GitHub Desktop.
Basic todos page
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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