Search code examples
react-nativenested-loops

Error in Nested map function React Native


I can't achieve to have two nested map with this below code i got [Error: Text strings must be rendered within a <Text> component.]

const MyScreen = ({ route, navigation }) => {
const { fieldsBlock } = route.params;
// Iterate
const fieldItems = fieldsBlock.map((fieldBlock) => (
    <View>
      <Text>{fieldBlock.title}</Text>
      {fieldBlock.fields.map((field) => (
        <Text>{field.fieldValue}</Text>
      ))}
    </View>
  )
);
return (
  <View>
    {fieldItems}
  </View>
);

};

Only if i use one map function then it works but with the nested map function it give an error.


Solution

  • I think, that the problem is that if fieldItems results in an empty array, you will be trying to render nothing between View tags.

    I suggest to change your code to render null if arrays are empty, like this

    const MyScreen = ({ route, navigation }) => {
      const { fieldsBlock } = route.params;
      // Iterate
      const fieldItems = fieldsBlock.map((fieldBlock) => (
          <View>
            <Text>{fieldBlock.title}</Text> // <-- NOTE: because of this, view is not empty
            {(fieldBlock && fieldBlock.fields && fieldBlock.fields.length)
               ? fieldBlock.fields.map((field) => (
                    <Text>{field.fieldValue}</Text>
                 ))
               : null
            }
          </View>
        )
      );
      return (
        {fieldItems && fieldItems.length)
          ? <View>{fieldItems}</View> : null // <-- NOTE: In this case avoid render a view without children
        }
      );
    };
    
    

    It is fine to render this:

    <View />
    

    but not this:

    <View>
    </View>
    

    Cheers!