jamesvphan jamesvphan - 3 years ago 271
React JSX Question

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:

// Also tried declaring function like below, but then I have no reference to user id.

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.

Answer Source

You can use .bind like this :

onAfterOpen={this.props.getInfo.bind(this, id)}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download