- React Material:UI Cookbook
- Adam Boduch
- 270字
- 2021-06-24 15:49:43
There's more...
You can mark ListItem components as selected by setting the selected property to true. You can also change the icon to give a better visual indication that an item has been selected. Here's the updated code:
import React, { useState } from 'react';
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 AccountCircleIcon from '@material-ui/icons/AccountCircle';
import CheckCircleOutlineIcon from '@material-ui/icons/CheckCircleOutline';
const MaybeSelectedIcon = ({ selected, Icon }) =>
selected ? <CheckCircleOutlineIcon /> : <Icon />;
export default function ListIcons() {
const [items, setItems] = useState([
{ name: 'First User' },
{ name: 'Second User' },
{ name: 'Third User' }
]);
const onClick = index => () => {
const item = items[index];
const newItems = [...items];
newItems[index] = { ...item, selected: !item.selected };
setItems(newItems);
};
return (
<List>
{items.map((item, index) => (
<ListItem
key={index}
button
selected={item.selected}
onClick={onClick(index)}
>
<ListItemText primary={item.name} />
<ListItemIcon>
<MaybeSelectedIcon
selected={item.selected}
Icon={AccountCircleIcon}
/>
</ListItemIcon>
</ListItem>
))}
</List>
);
}
Here's what the list looks like with First User selected:

The icon for the selected items changes into a circled checkmark. Let's break down the changes that were introduced to make this happen, starting with the MaybeSelectedIcon component:
const MaybeSelectedIcon = ({ selected, Icon }) =>
selected ? <CheckCircleOutlineIcon /> : <Icon />;
This component will render either CheckCircleOutlineIcon or the Icon component that is passed in as a property. This depends on the selected property. Next, let's look at how this component is used inside ListItemIcon:
<ListItemIcon>
<MaybeSelectedIcon
selected={item.selected}
Icon={AccountCircleIcon}
/>
</ListItemIcon>
When a list item is clicked on, the selected state for that item is toggled. Then, the selected state is passed to MaybeSelectedIcon. The AccountCircleIcon component is the icon that's rendered when the list item isn't selected, because it's passed to the Icon property.