Search code examples
reactjsreact-nativeconditional-statementsarray-map

React native if else condition in array map


I'm new to developing with React-Native and I'm developing a small application for the game of fantasy football.

I have created a component through which I show the starting players chosen by the user. I was able to cycle the array containing the players and show them correctly once the application started.

Within the cycle, however, I need to insert an if..else if ... else construct since I have to show the players based on their position (goalkeeper, defender, midfielder, attacker).

I've read some guides online, and some posts here on stack and then tried to put the conditional construct in my component, but when I run the app I get the following error: Component Exception: Text strings must be rendered with a <Text> component .

I don't know why he is doing this and what the mistake is ... do you have any suggestions or advice?

MY COMPONENT:

import React from 'react';
import {View, ScrollView, StyleSheet, Dimensionens, ImageBackground, Text} from 'react-native';
import { Entypo } from '@expo/vector-icons';
import HeaderComponent from '../commoncomponents/HeaderComponent';
import { List } from 'react-native-paper';

const FormazioneDetail2 = () => {
    //dichiariamo nome, cognome e posizione del giocatore
    const title = <View><Text>Nome {'\n'}Cognome {'\n'}GK </Text></View>;
    const player = [
        {
            key: '1',
            posizione: 'P',
            name: 'Donnarumma',
        },
        {
            key: '2',
            posizione: 'D',
            name: 'Bonucci',
        },
        {
            key: '3',
            posizione: 'D',
            name: 'Chiellini',
        },
        {
            key: '4',
            posizione: 'D',
            name: 'Bastoni',
        },
        {
            key: '5',
            posizione: 'C',
            name: 'Barella',
        },
        {
            key: '6',
            posizione: 'C',
            name: 'Jorjino',
        },
        {
            key: '7',
            posizione: 'C',
            name: 'Verratti',
        },
        {
            key: '8',
            posizione: 'C',
            name: 'Locatelli',
        },
        {
            key: '9',
            posizione: 'A',
            name: 'Insigne',
        },
        {
            key: '10',
            posizione: 'A',
            name: 'Immobile',
        },
        {
            key: '11',
            posizione: 'A',
            name: 'Berardi',
        }
    ]; 
    
    //ciclo per mostrare l'array di calciatori
    const list = () => {
        
        return player.map((element) => {
            return (
                <View style={styles.centeredView}>
                    <View style={styles.modalView}>
                        if(element.posizione == 'P'){
                            <View key={element.key}>
                            <Text style={{flex:5, marginTop: 5, alignItems: 'flex-end', flexDirection: 'row'}}>{element.name}: {element.posizione}</Text>
                            </View>
                        }else if(element.posizione == 'D'){
                            <View key={element.key}>
                            <Text style={{flex:5, marginTop: 10, alignItems: 'flex-end', flexDirection: 'row'}}>{element.name}: {element.posizione}</Text>
                            </View>
                        }else if(element.posizione == 'C'){
                            <View key={element.key}>
                            <Text style={{flex:5, marginTop: 15, alignItems: 'flex-end', flexDirection: 'row'}}>{element.name}: {element.posizione}</Text>
                            </View>
                        }else{
                            <View key={element.key}>
                            <Text style={{flex:5, marginTop: 20, alignItems: 'flex-end', flexDirection: 'row'}}>{element.name}: {element.posizione}</Text>
                            </View>
                        }
                                    
                    </View>
                </View>
            );
        });  
    };

    return (
            <View>
                <Text style={styles.screenTitle}>Formazione inserita</Text>
                <View>{list()}</View>
            </View>
            );
};

const styles = StyleSheet.create({

});

export default FormazioneDetail2;


Solution

  • You can't have if statements inside your return statement like that.

    You can do if statements like this:

    return (
      <div>
        {a === b ? <Text>A is equal to B</Text> : <Text>A is not equal to B</Text>}
      </div>
    )
    

    But in this case I would recommend extracting the if statement to it's own function like this:

    const getTextElement = (element) => {
      if (element.posizione === 'P') {
        return <Text style={{flex: 5, marginTop: 5, alignItems: 'flex-end', flexDirection: 'row'}}>{element.name}: {element.posizione}</Text>;
      } else if (element.posizione === 'D') {
        return <Text style={{flex: 5, marginTop: 10, alignItems: 'flex-end', flexDirection: 'row'}}>{element.name}: {element.posizione}</Text>;
      } else if (element.posizione === 'C') {
        return <Text style={{flex: 5, marginTop: 15, alignItems: 'flex-end', flexDirection: 'row'}}>{element.name}: {element.posizione}</Text>;
      } else {
        return <Text style={{flex: 5, marginTop: 20, alignItems: 'flex-end', flexDirection: 'row'}}>{element.name}: {element.posizione}</Text>;
      }
    };
    
    const list = () => {
      return player.map((element) => {
        const textElement = getTextElement(element)
    
        return (
          <View key={element.key} style={styles.centeredView}>
            <View style={styles.modalView}>
              <View>
                {textElement}
              </View>
            </View>
          </View>
        );
      });
    };
    

    I also moved the key to the top element inside the map function.