Reputation: 87
Sorry this is newbie question, usually using <List>{this.state.variable.map...}</List>
when in the component.But how to use .map function/any function inside conditional rendering in ternary operator?It was gave error syntax when using this syntax in below
Code:
{group.category !== "place" ?
<ListItem
title={"Foods"}
leftIcon={{
name: "food",
type: "material-community",
color: this.state.themeStore.primaryDarkColor
}}
subtitle={group.category}
subtitleStyle={{
color: this.state.themeStore.primaryDarkColor
}}
titleStyle={{ color: this.state.themeStore.primaryDarkColor }}
onPressRightIcon={() => {
this.showFoodsItem();
}}
rightIcon={{
name: "md-arrow-dropdown-circle",
type: "ionicon",
color: this.state.themeStore.primaryLightColor
}}
/>
this.state.foods.map((item, i) => (
<ListItem
key={i}
title={item.name}
titleStyle={{
color: this.state.themeStore.primaryDarkColor
}}
avatar={{ uri: item.imageSource }}
rightIcon={{
name: "md-add-circle",
type: "ionicon",
color: this.state.themeStore.primaryLightColor
}}
onPressRightIcon={() => this.addExistingPlace(item)}
/>
)
: (
<View />
)}
Upvotes: 0
Views: 2394
Reputation: 4570
It is not a problem with ternary operator. React expects that you'll return single child (or in a case of React 16+ - array of children) but you have multiple children.
You can workaround this problem by refactoring your code in a way that it will prepare array of <ListItem>
as separate block of code (but outside of return
statement of render()
method) and then either put this array directly into returned JSX tree (in a case of React 16+) or by using additional wrapper like React.createElement('div',{},...listItems)
So your code may look like this:
render() {
let items = [
<ListItem
title={"Foods"}
leftIcon={{
name: "food",
type: "material-community",
color: this.state.themeStore.primaryDarkColor
}}
subtitle={group.category}
subtitleStyle={{
color: this.state.themeStore.primaryDarkColor
}}
titleStyle={{color: this.state.themeStore.primaryDarkColor}}
onPressRightIcon={() => {
this.showFoodsItem();
}}
rightIcon={{
name: "md-arrow-dropdown-circle",
type: "ionicon",
color: this.state.themeStore.primaryLightColor
}}
/>
];
this.state.foods.forEach((item, i) => (
items.push(<ListItem
key={i}
title={item.name}
titleStyle={{
color: this.state.themeStore.primaryDarkColor
}}
avatar={{uri: item.imageSource}}
rightIcon={{
name: "md-add-circle",
type: "ionicon",
color: this.state.themeStore.primaryLightColor
}}
onPressRightIcon={() => this.addExistingPlace(item)}
/>
)
));
return group.category !== "place" ? React.createElement('div', {}, ...items) : <View/>;
}
Upvotes: 2