Reputation: 329
react beginner here after not being able to find any helpful leads while googling.
Given a list of data, in which each data describes what a ListItem
should contain, how can I dynamically create and return a List of ListItems? Each of the ListItem
is different (e.g. some have buttons, some dont)
const listData = [
{
"isClickable":true,
"horizontalComponents":[
{
"type": "image",
"data": {
"url": "http://tiny.co/foobar123"
}
},
{
"type": "text",
"componentData": {
"content": "This is a descriptive text. To view more please click the button on the right."
}
},
{
"type": "button",
"componentData": {
"buttonString": "View More"
}
}
]
}
];
listData.forEach(itemData => {
var columns: typeof ListItemText[] = [];
itemData.horizontalComponents.forEach(component => {
if (component.type == "text") {
columns.push(
<ListItemText primary={`Line item foo`} />
)
}
})
})
Upvotes: 2
Views: 865
Reputation: 14191
React components accepts array as children, so you may opt to use map
to return an array of ListItem
const listData = [
{
"isClickable": true,
"horizontalComponents": [
{
"type": "image",
"data": {
"url": "http://tiny.co/foobar123"
}
},
{
"type": "text",
"componentData": {
"content": "This is a descriptive text. To view more please click the button on the right."
}
},
{
"type": "button",
"componentData": {
"buttonString": "View More"
}
}
]
}
];
function App() {
return (
<List>
{listData.map((listitem, index) => (
<ListItem key={index}>
{listitem.horizontalComponents.map((component, index) => {
if (component.type === "text") {
return (
<ListItemText key={index}>{component.componentData.content}</ListItemText>
);
} else if (component.type === "button") {
return <Button key={index} variant="contained">{component.componentData.buttonString}</Button>;
}
})}
</ListItem>
))}
</List>
);
}
ReactDOM.render(<App/>, document.getElementById("root"));
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script src="https://unpkg.com/@material-ui/core@latest/umd/material-ui.development.js"></script>
<script type="text/babel">
const { List, ListItem, ListItemText, Button } = MaterialUI;
</script>
</body>
Upvotes: 1