Passing a function as a parameter that will be an onClick event

Holden1515

I have a function that returns a React.ReactElement obejct. I want to pass that function a function that is assigned to an onClick button event.

I call the function:

this._createInjurySection1Drawer([{innerDrawer: this._createInjurySection2Drawer, shouldShow:this._OnClickCloseInjurySection2}])

The function:

private _createInjurySection1Drawer(innerDrawers: any[]): React.ReactNode {

    ...

    let innerDrawer;
    let shouldShow;

    console.log("_createInjurySection1Drawer | innerDrawers: ", innerDrawers);

    if (innerDrawers && innerDrawers.length > 0) {
        innerDrawer = innerDrawers[0].innerDrawer;
        shouldShow = innerDrawers[0].shouldShow;
        innerDrawers.shift();
    }

    return (
        <Drawer
            ...
        >
            <div>
                {sectionOneForm.CreateSection(inputFieldsInjurySection1)}

                {innerDrawer && 
                    innerDrawer(innerDrawers)
                }
                <br/> <br/>
                <div>
                    <Button onClick={shouldShow()} type="primary">Next</Button>
                </div>
            </div>
        </Drawer>
    );
}

When I run this, I create an infinite loop.

How can I pass a function to handle when the button is clicked?

Ben R.

Try

<Button onClick={shouldShow} type="primary">Next</Button>

For further explanation,

<Button onClick={shouldShow()} type="primary">Next</Button>

will actually invoke the shouldShow function, so the return value will be used as the onClick handler. This is fine if shouldShow itself returns a function, but doesn't work so well if it returns e.g. a string - what does "hello world"() mean?

<Button onClick={shouldShow} type="primary">Next</Button>

instead sets the function itself as the onClick handler - "when I'm clicked, invoke this function, but not until then."

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related