- React Material:UI Cookbook
- Adam Boduch
- 273字
- 2021-06-24 15:49:42
There's more...
This example could have used props instead of state, because the items never changed. Let's modify it so that the user can select items from the list. Here's what the new List markup looks like:
<List>
{items.map((item, index) => (
<ListItem
key={index}
button
dense
selected={item.selected}
onClick={onClick(index)}
>
<ListItemText
primary={item.name}
secondary={item.timestamp.toLocaleString()}
primaryTypographyProps={{
color: item.selected ? 'primary' : undefined
}}
/>
</ListItem>
))}
</List>
The selected property passed to the ListItem component will apply selected styles to the item when true. This value comes from the item.selected state, which is false by default for every item (nothing is selected). Next, the ListItem component has an onClick handler.
The ListItemText component also has styles applied to it based on the selected state of the item. Behind the scenes, item text is rendered using the Typography component. You can use the primaryTypographyProps property to pass properties to the Typography component. In this case, you're changing the color of the text to primary when it's selected.
Let's look at the onClick() handler as follows:
const onClick = index => () => {
const item = items[index];
const newItems = [...items];
newItems[index] = { ...item, selected: !item.selected };
setItems(newItems);
};
This is a higher-order function, which returns an event handler function based on the index argument. It toggles the selected state for the item at the given index.
Here's what the list looks like when First Item is selected:
![](https://epubservercos.yuewen.com/E00FB0/19470380001496806/epubprivate/OEBPS/Images/7ae5643d-2472-454a-bd5a-0104eea6d755.png?sign=1739553698-nvIvQNzs44jqWnx8sSEhAiqyEV6CZxAz-0-3a74bb09cd82dc7742f85d76f52a1938)
The change to the background color is caused by the selected property of ListItem. The change to the text color is caused by the primaryTypographyProps property of ListItemText.