How to Break map() Loop in React Native?

Jul 30, 2022 . Admin



We are using map() function for display data in loop. sometimes we need to break map loop in react native then there is a not any specific method to break in map. but we can use filter() to break map() loop in react native app.

In this example, we will take users with different countries, then we will only display "India" and "USA" country users. other country users will skip. so let's see below example.

Step 1: Download Project

In the first step run the following command to create a project.

expo init ExampleApp
Step 2: App.js

In this step, You will open the App.js file and put the code.

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View } from 'react-native';
import {useState,useEffect} from 'react';

export default function App() {

  /*------------------------------------------
  --------------------------------------------
  Users Lists
  --------------------------------------------
  --------------------------------------------*/
  const users = [
    {id: 1, name: 'Hardik', country: 'India'},
    {id: 2, name: 'Vimal', country: 'India'},
    {id: 3, name: 'Harshad', country: 'Canada'},
    {id: 4, name: 'Keval', country: 'Denmark'},
    {id: 5, name: 'Savan', country: 'USA'},
  ];

  return (
    <View style={styles.container}>
      {users
        .filter(user => {
          return (
            user.country === 'India' || user.country === 'USA'
          );
        })
        .map((user, index) => {
          return (
            <div key={index}>
              <h2>Name: {user.name}</h2>
              <h2>Country: {user.country}</h2>
              <hr />
            </div>
          );
        })}
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});
Step 3: Run Project

In the last step run your project using the below command.

expo start

You can QR code scan in Expo Go Application on mobile.

Output:

It will help you...

#React Native