Created
December 30, 2019 23:02
-
-
Save shayan-ys/9d00c719331610d982a6a74900463b0a to your computer and use it in GitHub Desktop.
Simple TodoList in ReactJS with check/uncheck by click
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 cx from 'classnames'; | |
import { Component } from 'react'; | |
/* | |
assuming we wanted only ONE component, otherwise, naturally I would've make different components for each, TodoList, TodoItem, Input etc. | |
*/ | |
export default class TodoList extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
todoList: {}, | |
count_total: 0, | |
count_incomplete: 0, | |
new_todo_value: '' | |
}; | |
this.handleNewTodoChange = this.handleNewTodoChange.bind(this); | |
} | |
cross(id) { | |
this.setState(function(state, props){ | |
let crossed = !state.todoList[id]['completed']; | |
this.state.count_incomplete += crossed ? -1 : 1; | |
state.todoList[id]['completed'] = crossed; | |
return {todoList: state.todoList}; | |
}); | |
} | |
addTodo() { | |
this.setState(function(state, props){ | |
// todoList items should not be empty | |
if (state.new_todo_value.trim() == "") { | |
return {new_todo_value: ''}; | |
} | |
state.todoList[state.count_total] = {id: state.count_total, text: state.new_todo_value, completed: false}; | |
return { | |
new_todo_value: '', | |
todoList: state.todoList, | |
count_total: state.count_total + 1, | |
count_incomplete: state.count_incomplete + 1 | |
}; | |
}); | |
} | |
handleNewTodoChange(event) { | |
this.setState({new_todo_value: event.target.value}); | |
} | |
render() { | |
return ( | |
<> | |
<div> | |
<h2> | |
Todo List | |
</h2> | |
</div> | |
<style>{` | |
.is-done { | |
text-decoration: line-through; | |
} | |
`}</style> | |
<ul> | |
{Object.values(this.state.todoList).map((todo) => | |
<li data-id={todo.id} class={todo.completed ? 'is-done' : ''} onClick={(e) => this.cross(todo.id, e)}>{todo.text}</li> | |
)} | |
</ul> | |
<input type="text" value={this.state.new_todo_value} onChange={this.handleNewTodoChange} /> | |
<button onClick={(e) => this.addTodo(e)}>Add</button> | |
<p>{this.state.count_incomplete} remaining out of {this.state.count_total} tasks</p> | |
</> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment