Skip to content

[ClickAwayListener] Expose a hook API #18689

@Izhaki

Description

@Izhaki

I needed ClickAwayListener, but a hook rather than a component.

So I went ahead and extracted it from this repo, and now considering a PR here. A hook will shrink the component code to this:

const ClickAwayListener = React.forwardRef(function ClickAwayListener(props, ref) {
  const { children } = props;
  const clickAwayRef = useClickAway(props, ref);
  const handleRef = useForkRef(children.ref, clickAwayRef);
  return <React.Fragment>{React.cloneElement(children, { ref: handleRef })}</React.Fragment>;
});

Before, a couple of questions:

document vs ownerDocument

Event subscription happens on document, whereas the contain check happens on ownerDocument.

I guess as no bugs were filed this works alright. But in more than a few DnD libraries out there subscription happens on ownerDocument (eg, to support iframe).

So why subscribe on document rather ownerDocument?

Why function and not arrow function?

As in with:

function mapEventPropToEvent(eventProp) {
  return eventProp.substring(2).toLowerCase();
}

Is there some convention in the code regarding when to use one or the other?

Metadata

Metadata

Assignees

No one assigned

    Labels

    scope: click away listenerThis is the name of the generic UI component, not the React module!type: new featureExpand the scope of the product to solve a new problem.waiting for 👍Waiting for upvotes. Open for community feedback and needs more interest to be worked on.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions