react-onclickoutside icon indicating copy to clipboard operation
react-onclickoutside copied to clipboard

Is there any way to use this plugin with `render prop` pattern instead of `HOC`?

Open frederikhors opened this issue 7 years ago • 7 comments
trafficstars

Is there any way to use this plugin with render prop pattern instead of HOC?

frederikhors avatar Oct 07 '18 15:10 frederikhors

Can you show a use case in which this would be useful? (and other established patterns are insufficient)

Pomax avatar Oct 19 '18 18:10 Pomax

React, { useState } from "react";
import onClickOutside from "react-onclickoutside";

const Menu = () => {
  const [isOpen, setIsOpen] = useState(false);
  const toggle = () => setIsOpen(!isOpen);
  Menu.handleClickOutside = () => setIsOpen(false);
  return (
      //...
  )
};

const clickOutsideConfig = {
  handleClickOutside: () => Menu.handleClickOutside
};

export default onClickOutside(Menu, clickOutsideConfig);

VS

React, { useState } from "react";
import onClickOutside from "react-onclickoutside";

const Menu = () => {
  const [isOpen, setIsOpen] = useState(false);
  const toggle = () => setIsOpen(!isOpen);

  return (
      <OnClickOutside onOutsideClick={() => setIsOpen(false)}>
        ...
      </OnClickOutside>
  )
};

It will also solve https://github.com/Pomax/react-onclickoutside/issues/310 . @Pomax what do you think?

quolpr avatar Mar 05 '19 08:03 quolpr

You mean "can there be a regular Component that we can use"? (calling that "render prop" is a great way to confuse people =)

If so, I don't see why not, as long as it has a normal component name: onClickOutside is a function that yields an anonymous component, so if you want an explicit component we'd need to export something like OutsideClickMonitor or InnerClickIgnore or something. Depending on how much code needs to be changed to effect that, of course.

Pomax avatar Mar 06 '19 15:03 Pomax

I created such a Component since I ran into #310 as well.

import * as React from 'react'
import onClickOutside from 'react-onclickoutside'

class Comp extends React.Component<{ onClick: (e: Event) => void }> {
  public handleClickOutside = this.props.onClick
  public render() {
    return <React.Fragment>{this.props.children}</React.Fragment>
  }
}

export const OutsideClickMonitor = onClickOutside(Comp)

Would you like a pull request adding something like this @Pomax?

Knorrke avatar Mar 11 '19 15:03 Knorrke

That'd be great - as long as it comes with an update to the tests that uses it of course, because it'll need a baseline against which regressions can be found =)

Pomax avatar Mar 13 '19 17:03 Pomax

I wonder why it isn't like this from the beginning... Geniuine question, not a rhetorical one. I'm curious.

lorenzos avatar Jul 12 '19 13:07 lorenzos

Mostly because at the time this hoc was invented, around React 0.12, the syntax and functionality required to write that kind of code didn't existed in JS/React.

Pomax avatar Jul 24 '19 16:07 Pomax