14

I'm a React and React native noob so its probably going to be a very silly question but how can I use the 'for loop' inside the render function to include my components? This is what I did

render() {
  return (
    <View style={styles.container}>
      { for (let i=0; i<20; i++) 
        {
           //This is my component
           <CounterButton />
        }
      }
    </View>
  );
}

but it threw an error, then someone suggested to include the code in a method and call it inside the render function so I did

createButtons() {
  for (let i =0; i<20; i++){
    <CounterButton />;
  }
}

render() {
  return (
    <View style={styles.container}>
      {this.createButtons()}

    </View>
  );
}

now I dont see errors but its just a blank screen. I know you can access props but Is the render function supposed to contain primarily only JSX code? Thanks in advance.

WayneC
  • 5,569
  • 2
  • 32
  • 43
Dipanshu Juneja
  • 1,204
  • 14
  • 29
  • Same principle as React.js. Also see: [How to render repeating elements?](https://stackoverflow.com/questions/25646502/how-to-render-repeating-elements) and [How to loop and render elements in React.js without an array of objects to map?](https://stackoverflow.com/questions/29149169/how-to-loop-and-render-elements-in-react-js-without-an-array-of-objects-to-map). Also, one reason why you have a blank screen is because your function doesn't return anything to render. – Michael Cheng Aug 25 '17 at 15:07
  • when it is a blank screen, did you try with removing your `View`'s style? remove or post your `style={styles.container}` – Khalil Khalaf Aug 25 '17 at 15:42

2 Answers2

1

Your createButtons function doesn't return anything. You could add the buttons to an array and return that.

createButtons() {
  const buttons = [];
  for (let i =0; i<20; i++){
    buttons.push(<CounterButton />);
  }
  return buttons;
}

Note that in react-native when rendering an array of elements, each element needs to have a key property.

Kraylog
  • 7,383
  • 1
  • 24
  • 35
1

Jsx can contain expressions which return Components or arrays of components. In you case you need something that returns an array of components.

Sticking with the for loop:

createButtons() {
  let buttons = [];
  for (let i=0; i<20; i++){
    buttons.push(<CounterButton />);
  }
  return buttons;
}

If you wanted to do it in the jsx, something like this should work:

render() {
  return (
    <View style={styles.container}>
      {[...Array(20).keys()].map(<CounterButton />)}    
    </View>
  );
}
WayneC
  • 5,569
  • 2
  • 32
  • 43