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

Is it possible to pass down the triggerRef #16

Closed arnarp closed 4 years ago

arnarp commented 4 years ago

Hi.

Is it possible to do something like this


type Props = {
  triggerRef: React.RefObject<HtmlElement>
}

funciton Tooltip(props: Props) {
  return <ToggleLayer triggerRef={props.triggerRef />
}
everweij commented 4 years ago

Hi Arnar, I'm afraid that's not possible with , 'cause this component expects you to know the trigger element beforehand, but the hook variant useToggleLayer is more friendly and flexible regarding element ref's (see https://www.react-laag.com/docs/usetogglelayer/).

What are you trying to build? Maybe I can help you, and point you in the right direction ;)

arnarp commented 4 years ago

Hi. Thanks for your reply.

I was looking at the documentation for useToggleLayer but couldn't see how to give it the triggerRef. Do you maybe have any examples of that?

I'm building my own ui component library and I'm trying to create Tooltip component with this and framer motion.

It's important for me to own the refs, for example I have a button that triggers a dialog. I need the button ref to put the focus back on that button when the dialog closes. That's why I want my Tooltip component to get the triggerRef as a prop.

everweij commented 4 years ago

Thanks for your explanation, I've created two examples with CodeSandbox, hopefully they will clarify some things. I agree the docs about useToggleLayer should cover more use-cases etc... will try to work on that the next couple of days.

Example A - ToggleLayer with Downshift's useSelect (manages focus for you): https://codesandbox.io/s/select-menu-compound-8ds5e

Example B - useToggleLayer while 'owning' your own ref https://codesandbox.io/s/select-menu-usetogglelayer-xphuy

Note: If you just want access to the trigger-ref, you could also expose the trigger-ref to the outside as follows:

import mergeRefs from 'react-merge-refs';

const SelectMenu = React.forwardRef(function SelectMenu(props, forwardedRef) {
  return (
    <ToggleLayer
      // usual props...
    >
      {({ triggerRef}) => <div ref={mergeRefs(triggerRef, forwardedRef)} />}
    </ToggleLayer>
  );
});

// somewhere in your app...
function App() {
  const menuRef = React.useRef();

  React.useEffect(() => { /* do stuff with the ref... */}, [])

  return (
    <SelectMenu ref={menuRef} />
  )
}
arnarp commented 4 years ago

Thanks a lot for your help. Very helpful.

I decided to use useTogglelayer.

Here is what I made https://codesandbox.io/s/tooltip-9qu54

everweij commented 4 years ago

Awesome! Like how you made your tooltip component. Thanks for showing, and glad I could help :)