Created
February 4, 2020 20:54
-
-
Save thomas-lebeau/620264b0d0002dbd49ee3e64fefff0be to your computer and use it in GitHub Desktop.
todo
This file contains 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"; | |
import ReactDOM from "react-dom"; | |
function Todo(props) { | |
const { text, isDone, onToggle } = props; | |
const style = isDone ? { color: "grey", textDecoration: "line-through" } : {}; | |
return ( | |
<li> | |
<input | |
id={text} | |
name={text} | |
type="checkbox" | |
onChange={onToggle} | |
checked={isDone} | |
/> | |
<label htmlFor={text} style={style}> | |
{text} | |
</label> | |
</li> | |
); | |
} | |
class SimpleReminder extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
inputValue: "", | |
todos: [ | |
{ displayText: "foo", isDone: true }, | |
{ displayText: "bar", isDone: false }, | |
{ displayText: "baz", isDone: false } | |
] | |
}; | |
} | |
handleChange = event => { | |
this.setState({ | |
inputValue: event.target.value.trimLeft() | |
}); | |
}; | |
addTodo = () => { | |
this.setState(previousState => { | |
const prevInputValue = previousState.inputValue.trim(); | |
if (!prevInputValue) { | |
return {}; | |
} | |
return { | |
inputValue: "", | |
todos: [ | |
...previousState.todos, | |
{ displayText: prevInputValue, isDone: false } | |
] | |
}; | |
}); | |
}; | |
onToggle = index => { | |
this.setState(previousState => { | |
const newTodos = [...previousState.todos]; | |
newTodos[index].isDone = !newTodos[index].isDone; | |
return { | |
todos: newTodos | |
}; | |
}); | |
}; | |
render() { | |
const totalTodos = this.state.todos.length; | |
const doneTodos = this.state.todos.filter(todo => todo.isDone).length; | |
const percent = Math.round((doneTodos / totalTodos) * 100); | |
return ( | |
<div> | |
<input | |
type="text" | |
placeholder="Some reminder" | |
value={this.state.inputValue} | |
onChange={this.handleChange} | |
/> | |
<button onClick={this.addTodo}>Add todo</button> | |
<p>Today I need to remember to... </p> | |
<ul> | |
{this.state.todos.map((todo, i) => ( | |
<Todo | |
key={i} | |
text={todo.displayText} | |
isDone={todo.isDone} | |
onToggle={() => this.onToggle(i)} | |
/> | |
))} | |
</ul> | |
<div> | |
done: {doneTodos}/{totalTodos} ({percent}%){" "} | |
{percent >= 100 ? "🎉" : ""} | |
</div> | |
</div> | |
); | |
} | |
} | |
const rootElement = document.getElementById("root"); | |
ReactDOM.render(<SimpleReminder />, rootElement); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment