[SalesForce] Dynamically Generated Modal Lightning Component, Button Not Working as Intended

Creating a lightning component and I have two methods in the helper class which a) dynamically create two lightning components (buttons) and a modal popup and b) a method for the onclick of one of these buttons which closes the window.

The modal window is rendering correctly with the buttons as intended, but the "handleCancel" method is firing on modal load, NOT on the "onclick" of the button. Code is below, any suggestions are appreciated.

handleShowModal: function(component, evt, helper) {
    $A.createComponents(
        [
            ["lightning:button",
            {
                "aura:id": "cancelButton",
                "label": "Cancel",
                "onclick": helper.handleCancel(component)               
            }],
            ["lightning:button",
            {
                "aura:id": "mergeButton",
                "label": "Merge"
            }]
        ],
        function(comp, status) {
            if (status === "SUCCESS") {
                component.find('overlayLib').showCustomModal({
                    header: "Confirm Merge",
                    body: "Are you sure you wish to merge the below records?", 
                    footer: comp,
                    showCloseButton: true
                });
            }
        }
    );
},
//closes the modal
handleCancel : function(component) {
    console.log("button pressed");  
    console.log("the comp "+component.find("overlayLib"));
    component.find('overlayLib').notifyClose();
}

Best Answer

handleShowModal: function(component, evt, helper) {
    $A.createComponents(
        [
            ["lightning:button",
            {
                "aura:id": "cancelButton",
                "label": "Cancel",
                "onclick": cmp.getReference("c.handleCancel")               
            }],
            ["lightning:button",
            {
                "aura:id": "mergeButton",
                "label": "Merge"
            }]
        ],
        function(comp, status) {
            if (status === "SUCCESS") {
                component.find('overlayLib').showCustomModal({
                    header: "Confirm Merge",
                    body: "Are you sure you wish to merge the below records?", 
                    footer: comp,
                    showCloseButton: true
                });
            }
        }
    );
}

Your handle cancel should be a function of js Controller.

https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/js_cb_dynamic_cmp_async.htm