jamesvphan
jamesvphan

Reputation: 205

React Modal - call function with params onClick, not on render

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.

Upvotes: 2

Views: 3118

Answers (1)

Dan Oranen
Dan Oranen

Reputation: 51

You can use .bind like this :

onAfterOpen={this.props.getInfo.bind(this, id)}

Upvotes: 2

Related Questions