1

The issue I'm stuck on has to do with calling a function when a user clicks on a button, which will open a modal. The purpose of the function is to make a GET request for user information to populate the modal. I'm using the react-modal package, which accepts an onAfterOpen prop. I know I can use this prop to call my function, but to make the GET request, I also need pass in an id to the request.

My modal is set up as follows:

  <Modal
     isOpen={this.props.isSelected}
     onRequestClose={this.props.closeModal}
     onAfterOpen={this.props.getInfo(id)}
     // Also tried declaring function like below, but then I have no reference to user id.
     onAfterOpen={this.props.getInfo}
     contentLabel="Hello"
  >
  </Modal>

Issue with declaring my function like this is that my page renders a list of buttons, which is tied to a modal. So on render, this.props.getInfo(id) will be called.

For example, my container component will render a list of Button Components (say 9), and if each Button component contains a Modal component, then the function will get called 9 times.

jamesvphan
  • 195
  • 1
  • 4
  • 14

1 Answers1

2

You can use .bind like this :

onAfterOpen={this.props.getInfo.bind(this, id)}
Serge K.
  • 5,303
  • 1
  • 20
  • 27
Dan Oranen
  • 51
  • 3
  • Wouldn't `onAfterOpen={(id)=>this.props.getInfo(id)}` work too ? – Serge K. Sep 29 '17 at 22:09
  • Thanks for that! I ended up using Nathan's suggestion, worked like a charm! Is there a difference from writing it: like (id)=>this.props.getInfo(id) vs ()=>this.props.getInfo(id)? – jamesvphan Sep 30 '17 at 14:54
  • I wouldn't think Nathan's suggestion would work. When the function is called which is set to onAfterOpen, it probably isn't passed the id argument automatically? – Dan Oranen Oct 02 '17 at 16:31