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
First, you would want the removeItem method to exist in the Todos class, since that is where that state is stored. Then, you can either use filter or slice
export default class Todos extends Component {
constructor(props) {
super(props);
this.state = { todos: [], text: '' };
}
addTodo(e) {
e.preventDefault();
this.setState({ todos: [ this.state.text, ...this.state.todos ] });
this.setState({ text: ''});
}
updateValue(e) {
this.setState({ text: [e.target.value]})
}
removeItem = index => {
//either use filter
const { todos } = this.state;
const newTodos = todos.filter((todo, i) => i !== index);
this.setState({ todos: newTodos});
//or use slice
const slicedNewTodos = todos.slice(0, index).concat(todos.slice(index + 1));
this.setState({ todos: slicedNewTodos});
}
render() {
return(
);
}
}
import React, { Component } from 'react';
import { connect } from 'react-redux';
class TodoList extends Component {
render() {
return(
{ this.props.todos.map((todo, index) => {
return - this.props.removeItem(index)} key={todo}>{ todo }
})}
);
}
}