0

In react native in jsx i want a function to return a loop like these, I am doing like this but my code is saying unreachable in this case.

<View>
  {()=>{
   return ( for(var i=0;i<5;i++){
               <Text>Hello World</Text>
          })
   }}
</View>
jordan
  • 9
  • 1

3 Answers3

2

You can only render a React element.

Here is a simple example, although for loops are barely used.

let content = [];
for (let i = 0; i < 5; i++) {
  content.push(<h1>Hello World using for loop</h1>);
}

const App = () => {
  return (
    <div>
      {content}
      {[...Array(5).keys()].map((key) => (
        <h1 key={key}>Hello World using map</h1>
      ))}
    </div>
  );
};
Dennis Vash
  • 50,196
  • 9
  • 100
  • 118
  • I need for for loop because I need to use the property for-in in my condition also like for(var i in array){} – jordan Aug 20 '20 at 07:24
0

use map instead of loop.

Array.from({ length: 5 }).map((v) => <Text key={v}>{v}</Text>)
Prateek Thapa
  • 4,829
  • 1
  • 9
  • 23
0

Many solutions:

  1. Writing 5x Hello world

// Function

getList(){
    let texts = []
    for (let index = 0; index < 5; index++) {
        texts.push(<Text>Hello World</Text>)
    }
    return texts
}

// Render

<View>
    {this.getList()}
</View>
  1. Mapping an array of values

// Array

const list = [
    "Hello World",
    "Ad adipisicing ea ut in officia.",
    "Consectetur ipsum commodo reprehenderit sit est aliquip commodo ad qui duis et exercitation.",
    "Est sint esse veniam laborum cillum ullamco aliquip aute eiusmod cupidatat."
]

// Render

<View>
    {list.map((text, index) => <Text key={index}>{text}</Text>)}
</View>
BloodyMonkey
  • 1,572
  • 1
  • 9
  • 15