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>
3
  • Are you trying to display, Hello World 5x? Commented Aug 20, 2020 at 7:10
  • @bertdida yes i want to display 5 times Commented Aug 20, 2020 at 7:11
  • check out this answer -> stackoverflow.com/questions/11714503/does-return-stop-a-loop Commented Aug 20, 2020 at 7:12

3 Answers 3

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>
  );
};
Sign up to request clarification or add additional context in comments.

1 Comment

I need for for loop because I need to use the property for-in in my condition also like for(var i in array){}
0

use map instead of loop.

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

Comments

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.