2

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.

1 Answer 1

2

You can use .bind like this :

onAfterOpen={this.props.getInfo.bind(this, id)}
Sign up to request clarification or add additional context in comments.

3 Comments

Wouldn't onAfterOpen={(id)=>this.props.getInfo(id)} work too ?
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)?
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?

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.