- React Material:UI Cookbook
- Adam Boduch
- 376字
- 2021-06-24 15:49:44
There's more...
If you use an Avatar with the icons in your list items, you can change the color of the Avatar and you can apply a badge to indicate unacknowledged actions to be taken. Let's modify the example so that each item in the items state can have a notifications property; that is, a number representing the number of unread messages for the category. If this number is greater than 0, you can change the Avatar color and display number of notifications in a badge. Here's what the result looks like:

The first item in the list has an Avatar that's using the primary theme color and a badge showing the number of notifications. The rest of the items don't have any notifications, so the Avatar color uses the default, and the badge isn't displayed.
Let's see how this is done, starting with the styles:
const styles = theme => ({
activeAvatar: {
backgroundColor: theme.palette.primary[theme.palette.type]
}
});
The activeAvatar style is applied to the Avatar component when the notifications state is a number greater than 0. It looks up the primary theme color based on the theme type (light or dark). Next, let's look at the state of the first item in the items array:
{
name: 'Unread',
updated: '2 minutes ago',
Icon: MarkunreadIcon,
notifications: 1
}
Because the notifications value is 1, the color of the avatar changes, and the badge is displayed. Lastly, let's see how all of this comes together in the component markup using the Badge and Avatar components:
<Badge
color={item.notifications ? 'secondary' : undefined}
badgeContent={
item.notifications ? item.notifications : null
}
>
<Avatar
className={clsx({
[classes.activeAvatar]: item.notifications
})}
>
<Icon />
</Avatar>
</Badge>
The color property of Badge is based on the notifications state of the item being greater than 0. If it is, the primary color is used. If it isn't, undefined is passed to Badge. In this case, this is necessary so that an empty badge circle doesn't show up when there aren't any notifications.
Next, the badgeContent property is set based on the notifications state of the item. If it's not greater than 0, then you don't want any value set. Finally, setting the color of the Avatar component uses clsx() to apply the activeAvatar class if the notifications state for the item is greater than 0.