Skip to content

Instantly share code, notes, and snippets.

@varmab
Created February 25, 2021 23:51
Show Gist options
  • Save varmab/71587398145efd4a0963ec65115102f4 to your computer and use it in GitHub Desktop.
Save varmab/71587398145efd4a0963ec65115102f4 to your computer and use it in GitHub Desktop.
import React, { Component } from 'react'
class Todos extends Component{
constructor(){
super();
this.state={
todos:[],
todo:'',
isEditing: false,
editingTodo:'',
editedTodo:''
}
}
onTodoChange=(e)=>{
var todo=e.target.value;
console.log(todo);
this.setState({
todo
})
}
onEditTodo=(todo)=>{
this.setState({isEditing: !this.state.isEditing,editingTodo:todo, editedTodo:todo});
}
onEditingTodoChange=(e)=>{
var todo=e.target.value;
console.log(todo);
this.setState({
editedTodo:todo,
isEditing:true
})
}
updateTodo=()=>{
console.log('Update todo')
var editingTodoIndex=this.state.todos.findIndex((currentTodo)=>{
return currentTodo==this.state.editingTodo
})
var currentTodos=Object.assign([],this.state.todos);
currentTodos[editingTodoIndex]=this.state.editedTodo;
this.setState({
todos:currentTodos
})
}
addTodo=()=>{
console.log("Adding todo")
this.setState({
todos:[...this.state.todos,this.state.todo],
todo:''
})
}
removeTodo=(todo)=>{
this.setState({
todos:this.state.todos.filter((currentTodo)=>{
return currentTodo!=todo
})
})
}
render(){
return(
<div>
<h1>Todos</h1>
<input type="text" value={this.state.todo} onChange={this.onTodoChange}/>
<button onClick={this.addTodo}>Add Todo</button>
<ul>
{
this.state.todos.map((todo,index)=>{
return <React.Fragment>
{
(this.state.isEditing && this.state.editingTodo==todo) ?
(<span key={index}><input value={this.state.editedTodo} type="text" onChange={this.onEditingTodoChange}/><button onClick={()=>this.updateTodo(todo)}>Update</button></span>)
:
(<li key={index}>{todo}<button onClick={()=> this.onEditTodo(todo)}>Edit</button><button onClick={()=> this.removeTodo(todo)}>Remove</button>
</li>)
}
</React.Fragment>
})
}
</ul>
</div>
)
}
}
export default Todos;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment