I have an issue I can't seem to crack even after checking out a few other posts on here and trying a few things out. I am playing around with React and making a quick todo list. Easy enough as I can add new names and display them on the page as intended. I want to be able to delete items that I choose and for that I was looking around and saw others doing something like this to delete items:
deleteName(id, e) {
const { names } = this.state;
this.setState({
names: names.filter(name => name.id !== id)
});
}
That made sense to me but I wasn't adding any id's to my <li>
items so I thought I could just do:
this.setState({
names: names.filter(name => name !== name)
});
But this will just delete the whole list. What am I doing wrong? Should I restructure how I add names to the array to have an id and check that? I'll post the full component code below. Any help I can get is always appreciated. Thanks guys.
class ContactListPage extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
names: []
};
this.addName = this.addName.bind(this);
this.deleteName = this.deleteName.bind(this);
}
addName(name) {
const { names } = this.state;
if (name === '') {
console.log('add a name first!')
} else {
this.setState({
names: names.concat(name)
});
}
}
deleteName(id, e) {
const { names } = this.state;
this.setState({
names: names.filter(name => name !== name)
});
}
render() {
const { names } = this.state;
const named = names.map((name, i) => (
<Card key={i} className='todo-list'>
<CardText>
<li>{name}
<FloatingActionButton className='fab-delete' mini onClick={this.deleteName}>
<i className="material-icons fab-icon-delete" style={{color: 'white'}}>-</i>
</FloatingActionButton>
</li>
</CardText>
</Card>
));
return (
<div className='contact-list'>
<div className="field-line">
<NewName addName={this.addName} />
<ul className='new-name'>
{named}
</ul>
</div>
</div>
);
}
}