Step 10
Let's add a method to the App
class for deleting a note.
deleteNote = (note) => {
this.setState((state) => {
return {
notes: state.notes.filter((n) => n.id !== note.id),
};
});
};
Notice
setState
is called with a function argument. This function receives the "current" state, and it will return the "modified" (updated) state.
Let's now pass this method as props to the Note component.
- <Note note={note} key={index} />
+ <Note note={note} key={index} deleteNote={this.deleteNote} />
Next, update the Note
component as follows
render() {
- const { note } = this.props;
+ const { note, deleteNote } = this.props;
const { open } = this.state;
return (
<>
- <ListItem onClick={this.handleClick}>
+ <ListItem>
- <ListItemIcon>
+ <ListItemIcon onClick={this.handleClick}>
{open ? <ExpandLess /> : <ExpandMore />}
</ListItemIcon>
<ListItemText primary={note.title} />
+ <ListItemIcon>
+ <Button onClick={() => deleteNote(note)}>
+ <Delete />
+ </Button>
+ </ListItemIcon>
</ListItem>
<Collapse in={open} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
<ListItemText secondary={note.text} />
</List>
</Collapse>
</>
);
}
Make sure that you update your import statements as well:
- import { Collapse, List, ListItem, ListItemText, ListItemIcon } from "@material-ui/core";
+ import { Collapse, List, ListItem, ListItemText, ListItemIcon, Button } from "@material-ui/core";
- import { ExpandLess, ExpandMore } from "@material-ui/icons";
+ import { ExpandLess, ExpandMore, Delete } from "@material-ui/icons";
Save the changes and visit the React app.