Bread
Bread

Reputation: 15

Is there a way to combine JSX element and additional code?

{this.state.categories && this.state.dishes && this.state.categories.map((item) => (
  <Text style={{fontSize: 30, fontWeight: 'bold', padding: 5, backgroundColor: '#f0f0f0', borderWidth: 0.175}}>{item['dish_categories_name']}</Text>
  this.filterDishesOnCategory(this.filterList(this.state.dishes), item['dish_categories_id']).map((listItem) => (
    <View key={listItem['dish_name']} >
      <Dish name={listItem['dish_name']} info={listItem['dish_description']} cost={listItem['dish_price']}/>
    </View>
  ))
))}

I'm trying to map over the categories data, which then produces a text element with the name of the category. Afterwards, the dishes that are within this category are mapped through and additional dish information is displayed. However, it is clear that the Text tag and this.filterDishesOnCategory cannot be together like this. What is a possible solution to this issue?

Upvotes: 0

Views: 92

Answers (1)

John
John

Reputation: 353

The reason this doesn't work is because the map can only return one parent component. There is something called Fragment made specifically for this kind of scenario. The Fragment component doesn't render any HTML and it serves to work for this situation where you need a parent element for the sole purpose of pleasing React.

You can import the Fragment component from the react package.

import React, { Fragment } from 'react';

So now we simply add a Fragment as a parent component and add curly braces to your this.filterDishesOnCategory method.

{this.state.categories && this.state.dishes && this.state.categories.map((item) => (
    <Fragment>
        <Text style={{fontSize: 30, fontWeight: 'bold', padding: 5, backgroundColor: '#f0f0f0', borderWidth: 0.175}}>{item['dish_categories_name']}</Text>
        {this.filterDishesOnCategory(this.filterList(this.state.dishes), item['dish_categories_id']).map((listItem) => (
            <View key={listItem['dish_name']} >
                <Dish name={listItem['dish_name']} info={listItem['dish_description']} cost={listItem['dish_price']}/>
            </View>
        ))}
    </Fragment>
))}

Upvotes: 1

Related Questions