Search code examples
reactjsreact-nativereact-native-iosreact-native-flatlist

how do I concatinate string response inside an array in React native?


I am accessing one string from a list of content, and I want to concatenate the strings with commas, however whenever I try to do so the style is breaking both for web and mobile.

Below is the code that I have written

<View style={{flexDirection: 'row'}}>
            {props.item.vaccine_list.map((item, i) => {
              console.log('teme', typeof item.name);
              return (
                <View
                  key={i}
                  style={
                    width > 414
                      ? {flexDirection: 'row', width: 35}
                      : {
                          flexDirection: 'row',
                          width: 30,
                        }
                  }>
                  <Text
                    style={{
                      fontFamily: 'Roboto',
                      fontSize: 12,
                      color: '#000',
                    }}>
                    {item.name + ','}
                  </Text>
                </View>
              );
            })}
          </View>

mobile view:

enter image description here

web view:

enter image description here

Please tell me how to fix the style and bring the strings together in a line cleanly as comma separated values.


Solution

  • If props.item.vaccine_list is the array of "strings" you want to concatenate then I suggest you map the name properties first, then join them with commas.

    props.item.vaccine_list.map(({ name }) => name).join(', ')
    

    Code

    <View style={{flexDirection: 'row'}}>
      <View
        style={
        width > 414
          ? {flexDirection: 'row', width: 35}
          : {
            flexDirection: 'row',
            width: 30,
          }}
      >
        <Text
          style={{
            fontFamily: 'Roboto',
            fontSize: 12,
            color: '#000',
          }}
        >
          {props.item.vaccine_list.map(({ name }) => name).join(', ')}
        </Text>
      </View>
    </View>