Search code examples
javascriptreactjsfunctionreact-nativereturn

React Native returning multiple JSX components in loop using another function


I would like to return multiple JSX components (Foodcards) using a loop. I used another function to return the component inside the loop. But the function is not returning the component. Foodcards is a component that takes name and rate as inputs. The code works fine when the component(Foodcards) is returned from renderMenu().

import React, { Component } from 'react'
import Dimensions from 'Dimensions'
import { Actions, ActionConst } from 'react-native-router-flux'
import * as firebase from 'firebase'


import GLOBALS from '../global/Globals';
import Background from '../Background.js';
import Foodcards from '../Foodcards.js';

const DEVICE_WIDTH = Dimensions.get('window').width;

import {
    StyleSheet,
    View,
    Text,
    TouchableOpacity,
    ScrollView,
    TextInput,
    ToastAndroid,
} from 'react-native'

export default class Foodview extends Component {

    returnFoodCard(text1, text2) {
        return <Foodcards Name={text1} Rate={text2} />
    }

    renderMenu() {
        var fetchedJSON = this.props.dishes;
        var fetchedString = JSON.stringify(fetchedJSON);
        var i = 0;
        var arrayOfLines = fetchedString.split(",")
        for (i = 0; i < arrayOfLines.length; i++) {
            var arr = arrayOfLines[i].split('$');
            ToastAndroid.show(arr[1], ToastAndroid.SHORT);
            this.returnFoodCard(this, arr[1], arr[2]);
        }
    }    

    render() {

        return (


            <View style={styles.Container}>

                {this.renderMenu()}

            </View>



        );
    }
}


const styles = StyleSheet.create({

    Container: {
        top: 5,
        flex: 1,
        backgroundColor: "white",
    },

    btnStyle: {
        backgroundColor: GLOBALS.linkTextColor,
        alignItems: 'center',
        top: 400,
        left: DEVICE_WIDTH / 2 - ((DEVICE_WIDTH - 250) / 2),
        paddingLeft: 8,
        width: DEVICE_WIDTH - 250,
        height: 30,
    },

    btnText: {
        left: -5,
        top: 5,
        color: "white"
    },

});


Solution

  • The problem is you are not returning anything from renderMenu method.

    Try something like this:

    renderMenu() {
        var fetchedJSON = this.props.dishes;
        var fetchedString = JSON.stringify(fetchedJSON);
        var i = 0;
        var arrayOfLines = fetchedString.split(",")
        return arrayOfLines.map((line) => {
            var arr = line.split('$');
            ToastAndroid.show(arr[1], ToastAndroid.SHORT);
            return this.returnFoodCard(arr[1], arr[2]);
        });
    }
    

    Also the returnFoodCard seems to take two arguments and you are passing in three...