jordan
jordan

Reputation: 9

How to loop inside return statement in javascript

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>

Upvotes: 0

Views: 419

Answers (3)

BloodyMonkey
BloodyMonkey

Reputation: 1634

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>

Upvotes: 0

Dennis Vash
Dennis Vash

Reputation: 53904

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>
  );
};

Upvotes: 2

Prateek Thapa
Prateek Thapa

Reputation: 4938

use map instead of loop.

Array.from({ length: 5 }).map((v) => <Text key={v}>{v}</Text>)

Upvotes: 0

Related Questions