create multiple buttons in a view via loop

2.5k views Asked by At

I want to create multiple custom buttons for my react-native app. I'm using an array with all the informations in it and I want to iterate over all buttons in the array and create all buttons in one single view. I tried something like this:

<View>
  for( let i=0; i<numberButtons; i++) {
          <TouchableOpacity style={[styles.mapView, this.props.mapViewStyle]} >
            <Image
              style={[styles.image, this.props.imageStyle]}
              source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}
            />
          </TouchableOpacity>
}
</View>

That doesn't seem to work. I get errors from the react-native framework so I guess you can't do js in a view?

How can I do this?

1

There are 1 answers

4
Matt Aft On BEST ANSWER

You can do it like this:

renderButtons = () => {
  const buttons = [];
  for( let i = 0; i < numberButtons; i++) {
     buttons.push(
      <TouchableOpacity style={[styles.mapView, this.props.mapViewStyle]}>
        <Image
          style={[styles.image, this.props.imageStyle]}
          source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}
        />
      </TouchableOpacity>
    )
  }
  return buttons;
}



render() {
  return (
    <View>
      {this.renderButtons()}
    </View>
  )
}