Home > Mobile >  Call function parameter inside child component in react
Call function parameter inside child component in react

Time:04-26

Since I am new to react, I have a function in my parent component like below

const openMenu = (item: Iitem) => {
    setNavOpen(item.id);
    closeMenu();
}

<ul>
    {navItems.map((navItem) => (
        <NavItem
            data={navItem}
            key={navItem.id}
            openMenu={openMenu}
        />
    ))}
</ul>

And I am trying to access the openMenu function from my child component

like this

<ItemButton
    id={data.id}
    onClick={openMegaMenu}
>
    Hello Test
</ItemButton>

I am trying to use the function like onClick={openMegaMenu(data)} but it throws an error like uncaught-typeerror-cannot-read-property-nextsibling-of-undefined . Can you please tell me what is the wrong here.

CodePudding user response:

You were close! You want to pass a function to be called, not call the function, so the following should work

onClick={() => openMegaMenu(data)}
  • Related