everweij / react-laag

Hooks to build things like tooltips, dropdown menu's and popovers in React
https://www.react-laag.com
MIT License
907 stars 47 forks source link

Docs: example of useToggleLayer.open() (e.g. on keyboard event) #37

Closed mtmacdonald closed 3 years ago

mtmacdonald commented 4 years ago

Is it possible to have an example of how to use the open() method from useToggle? I don't understand what the clientRect and target parameters are, where I can access them from, or why they need to be passed in order to open the layer.

More context: I'm trying to open the layer from a keyboard event (so I can't use the openFromMouseEvent() like I do when clicking through the GUI). I basically want an open() method I can call from a keyboard event.

mtmacdonald commented 4 years ago

For now, as a workaround, I was able to use a ref to simulate a click event, e.g. putting triggerRef.current.click() in the keyboard event handler.

everweij commented 3 years ago

Hi @mtmacdonald , In >= v2, you can open the layer from anywhere you like with useLayer() Example:

function Example() {
  const [isOpen, setOpen] = React.useState(false);

  const { layerProps, triggerProps, renderLayer } = useLayer({ isOpen });

  React.useEffect(() => {
     function handleKeyPress(evt) {
       if (evt.key === "Enter") {
         setOpen(true);
       }
     }

     document.addEventListener("keypress", handleKeyPress);

     return () => document.removeEventListener("keypress", handleKeyPress);
   }, [])

  return (
    <div>
      <button {...triggerProps} onClick={() => setOpen(!isOpen)}>trigger</button>
      {isOpen && renderLayer(<div {...layerProps}>Layer</div>)}
    </div>
  )
}

Does this help to solve your problem?

mtmacdonald commented 3 years ago

@everweij thanks a lot! The v2 improvements are great. I'm happy to close this ticket.