1
votes

I am trying to write a method to render buttons dynamically and am trying to avoid code repetition by using renderButton method. I cannot find a solid solution anywhere to this problem can anyone help? I am fairly new to react native

enter image description here

   export default class DialogBoxStory extends PureComponent {
  state = { isVisible: false, type: 'confirm' }

  hide (type) {
    return (payload = '') => {
      this.setState({ isVisible: false })
      console.debug(`hide ${type}`, payload)
    }
  }

  show (type) {
    return (payload) => {
      this.setState({ isVisible: true, type })
      console.debug(`show ${type}`, payload)
    }
  }

  renderButtons () {
    return [ 'confirm', 'alert', 'input' ]
      .map((type) => (
        <Button
          title={`show ${type} dialog`}
          type="primary"
          onPress={this.show(type)}
        />
      ))
  }


  render () {
    const options = {
      title: text('title', 'Test Title', 'props'),
      message: text('message', lorem, 'props'),
      onOkPress: this.hide('onOkPress'),
      onCancelPress: this.hide('onCancelPress'),
      isVisible: this.state.isVisible,
      type: this.state.type,
      onRequestClose: this.hide('onRequestClose'),
    }

    return (
      <Fragment>
        <DialogBox {...options} />
        {this.renderButtons}
      </Fragment>
    )
  }
}
1
it should be {this.renderButtons()} - Mayank Shukla
nope! still fails. It has to do with how I am returning buttons - Ackman
have you tried after removing this line: {this.renderButtons()} ? does it work after that? - Mayank Shukla
Yes! it still does not work - Ackman
Can you try adding return here? return <Button title={show ${type} dialog} type="primary" onPress={this.show(type)} /> - Just code

1 Answers

1
votes
  • Convert all your methods (functions) declarations to arrow function like show = () => {Your Function Body}

  • You have to call your renderButtons function {this.renderButtons()}

  • Also this part of the code onPress={this.show(type)} has to use bind() method and pass this keyword as the first param onPress={this.show.bind(this, type)}

Read more about bind() method