Reputation: 9
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
Reputation: 1634
Many solutions:
// Function
getList(){
let texts = []
for (let index = 0; index < 5; index++) {
texts.push(<Text>Hello World</Text>)
}
return texts
}
// Render
<View>
{this.getList()}
</View>
// 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
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
Reputation: 4938
use map instead of loop.
Array.from({ length: 5 }).map((v) => <Text key={v}>{v}</Text>)
Upvotes: 0