1

I use ContextualMenu inside a DetailsList column. But when I click the trigger, the menu appears for a short time and immediately closes. What am i doing wrong? Is it acting like this because there are multiple renders?

My code is like below

function MyComponent() {
   const [contextMenu, setContextMenu] = useState(false);
   const linkRef = useRef(null);

   const columns = [
      {
         key: "action",
         onRender: () => {
            return (
            <>
               <a ref={linkRef} onClick={() => setContextMenu(true)} href="#">
                 Click for ContextualMenu
               </a>
               <ContextualMenu
                 items={menuProps.items}
                 hidden={!contextMenu}
                 target={linkRef}
                 onItemClick={() => setContextMenu(false)}
                 onDismiss={() => setContextMenu(false)}
               />
            </>
            )
         }
      }
   ];
   
   return (
      <DetailsList
        items={data}
        columns={columns}
      />
   )
}
abdllhcay
  • 69
  • 2
  • 6
  • Here you are Codepen example https://codepen.io/savkelita/pen/dyZVwwq?editors=0010 i think everything works fine with provided code – Marko Savic Feb 15 '22 at 15:10
  • It's weird. I think the problem is with my render count. My code is rendering four times. Thank you anyway. – abdllhcay Feb 16 '22 at 13:04

1 Answers1

1

I've encountered a similar problem, you can check the onDismiss event, it should be triggered at least once, then check the type of that event, like this:

          <ContextualMenu
             items={menuProps.items}
             hidden={!contextMenu}
             target={linkRef}
             onItemClick={() => setContextMenu(false)}
             onDismiss={(event) => {
               console.log("event", event, event.type)
               setContextMenu(false)  
             }}
           />

If it's a focus event, it's very likely you encounter the same problem as mine: rendering multiple MyCompoennt with hidden !== false, you should be able to fix it by only displaying one contextualMenu at a time.

D3vtr0n
  • 2,774
  • 3
  • 33
  • 53