The for Loop in React Native

MD Aminul Islam Feb 02, 2024
The for Loop in React Native

Loops are the most used and common part of any programming language and framework. Sometimes we need to create multiple elements at a time dynamically.

We use loops for this purpose. But in React-Native, it’s a bit more difficult than in other programming languages.

This article will show using a for loop in React-Native.

Use for Loop in React Native

To use the for loop in a React app, we need to follow the below steps.

  1. First, we need to create an array object.
  2. Then, we need to run the for loop and push elements inside the array we created.
  3. We must pass that array to the return() function.

Let’s take a look at our below example, where we illustrated the use of the for loop in React-Native.

// importing necessary packages

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

export default function App() {
  let myLoop = [];  // Declaring an array

  for (let a = 0; a <= 5; a++) {  // For loop here
     myLoop.push(
       <Text>This is line {a} {'\n'}</Text>
     );
  }


  return ( // Showing the array element
    <View style={styles.container}>
      <Text>{myLoop}</Text>
      <StatusBar style="auto" />
    </View>
  );

}

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

The purpose of all necessary lines regarding the steps is left as comments in the code above. Now when you run the app, you will get the below output on your screen.

This is line 0
This is line 1
This is line 2
This is line 3
This is line 4
This is line 5

Please note that the code shared above is created in React-Native, and we used the Expo-CLI to run the app.

MD Aminul Islam avatar MD Aminul Islam avatar

Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.

LinkedIn

Related Article - React Native

Related Article - React Native Loop