I\'m doing a simple todo app with React, just to practise. How can I delete a list item, when clicking on it?
Here is my todos.js
export default cla
You have called setState two times in the addTodo function. You can set todos and text in a single setState function like this:
addTodo(e) {
e.preventDefault();
this.setState({ todos: [ this.state.text, ...this.state.todos ], text: '' });
}
Do not write removeItem function in TodoList Component as it is purely working on props. Pass a removeItem function from Todos to it and remove that item in Todos's removeItem function like this:
import React, {Component} from 'react'
export default class Todos extends Component {
constructor(props) {
super(props);
this.state = { todos: [], text: '' };
this.removeItem = this.removeItem.bind(this)
}
addTodo(e) {
e.preventDefault();
this.setState({ todos: [ this.state.text, ...this.state.todos ], text: '' });
}
updateValue(e) {
this.setState({ text: [e.target.value]})
}
removeItem(index) {
const todos = this.state.todos.filter((todo, todoIndex) => {
return todoIndex !== index
})
this.setState({ todos })
}
render() {
return(
);
}
}
class TodoList extends Component {
render() {
return(
{ this.props.todos.map((todo, index) => {
return - { this.props.removeItem(index)}} key={todo}>{ todo }
})}
);
}
}
Hope, it helps.