Home > Mobile >  Why can't I use onClick in the trigger of a Popup component in React?
Why can't I use onClick in the trigger of a Popup component in React?

Time:12-29

I have a table in which the last column of each row holds a Button that is intended to trigger a popup to "edit and save" certain values of that row in my React app. Part of the criteria was that clicking outside the popup would also close it while preventing the user from clicking things in the background until the popup closed.

To do this, I opted to use a package called reactjs-popup. Currently for all criteria, it works perfectly. The next step, though, was to run a function when the button is clicked so that I could pull data from the API to populate the fields. However, I found that I couldn't call any functions from the onClick of the button used as a trigger. This is the main snippet of code:

import Popup from 'reactjs-popup' // this is the npm package I used
// more react code, including an arbitrary loadInfo function
<Popup
    trigger = { 
        <Button onClick = {() => { loadInfo() }}
    }
    modal
    nested
>
{ close => (
    <div className = "modal1" id = "popupForm">
        // popup content with input forms with values to be populated
    </div>
}
</Popup>

The main problem I have is the "onClick" part of the Button in the trigger. No matter what I put in there, it is never ran when I click it. When I test the same button as a standalone, and not as the trigger for the popup, it works fine.

I also tried using

onClick = {loadData()}

But this just caused the function to constantly run as soon as it was rendered, and inevitable break due to too many renders. Does anyone know why this reactjs-popup component does not allow onClick within its trigger? And if so, how to get around it? Thanks!

CodePudding user response:

I believe you want to loadInfo when the popup opens.

For that, there is a prop onOpen in Popup which accepts a function . You can use that,

Or you can manually set open prop using state. Have a button outside popup and update the open state when it clicked.

  • Related