2

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 Answer 1

4

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

4 Comments

ok cool, thank you:) Can you explain why I can't iterate and do stuff the "normal" way?
Sure, anytime you want to use javascript you will have to put it into brackets { }, I believe whatever you return in the render will be read as JSX.
Oh wait. It seems like it is not working. Don't I need to return() the created touchableOpacity ?
something like this? exampleAlthough it's not working like that.

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.