- React Material:UI Cookbook
- Adam Boduch
- 123字
- 2021-06-24 15:49:41
How to do it...
Let's say that you have an array of three objects that you need to display as a list on one of your screens. You can add this array to the state of your component, then map each array item to a ListItem component. Here's the 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';
export default function UsingStatetoRenderListItems() {
const [items, setItems] = useState([
{ name: 'First Item', timestamp: new Date() },
{ name: 'Second Item', timestamp: new Date() },
{ name: 'Third Item', timestamp: new Date() }
]);
return (
<List>
{items.map((item, index) => (
<ListItem key={index} button dense>
<ListItemText
primary={item.name}
secondary={item.timestamp.toLocaleString()}
/>
</ListItem>
))}
</List>
);
}
Here's what you'll see when you first load the screen:
