- React Material:UI Cookbook
- Adam Boduch
- 259字
- 2021-06-24 15:49:43
How to do it...
Let's say that you have four categories of messages that can be displayed by your app. To access a given category, the user clicks on one of the list items. To help the user understand the categories, you'll use icons. And to make the icons stand out against the primary and secondary text of the list item, you'll wrap it with an Avatar component. Here's the code:
import React, { useState } from 'react';
import clsx from 'clsx';
import Avatar from '@material-ui/core/Avatar';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import MarkunreadIcon from '@material-ui/icons/Markunread';
import PriorityHighIcon from '@material-ui/icons/PriorityHigh';
import LowPriorityIcon from '@material-ui/icons/LowPriority';
import DeleteIcon from '@material-ui/icons/Delete';
export default function ListAvatarsAndText({ classes }) {
const [items] = useState([
{
name: 'Unread',
updated: '2 minutes ago',
Icon: MarkunreadIcon,
notifications: 1
},
{
name: 'High Priority',
updated: '30 minutes ago',
Icon: PriorityHighIcon
},
{
name: 'Low Priority',
updated: '3 hours ago',
Icon: LowPriorityIcon
},
{ name: 'Junk', updated: '6 days ago', Icon: DeleteIcon }
]);
return (
<List>
{items.map(({ Icon, ...item }, index) => (
<ListItem button>
<ListItemIcon>
<Avatar>
<Icon />
</Avatar>
</ListItemIcon>
<ListItemText
primary={item.name}
secondary={item.updated}
/>
</ListItem>
))}
</List>
);
}
Here's what the list looks like when rendered:
![](https://epubservercos.yuewen.com/E00FB0/19470380001496806/epubprivate/OEBPS/Images/d61c49f7-3d39-4b51-8fbc-ca11ddcf042b.png?sign=1739554216-4viyANcclPA7BT5UDyJcWQHlYhwi537f-0-474c5b4ae8abc4fbd5b8a6ea59f31301)
The circle that surrounds the icon is the Avatar component, and it helps the icon stand out. Here's what this list looks like without avatars:
![](https://epubservercos.yuewen.com/E00FB0/19470380001496806/epubprivate/OEBPS/Images/696b5773-89c1-45a4-a07f-45fc82433fac.png?sign=1739554216-PT8VUZkZOXz2yVCA52z2K76SAoWEdCNy-0-c43129a5c54fd78f86f45c8be025e25a)
It's the same content and the same icons, but because of the height of the list item text, there's a lot of excess space surrounding the icon. The Avatar component helps fill this space while drawing attention to the icon.