react-onclickoutside
react-onclickoutside copied to clipboard
Is there any way to use this plugin with `render prop` pattern instead of `HOC`?
Is there any way to use this plugin with render prop pattern instead of HOC?
Can you show a use case in which this would be useful? (and other established patterns are insufficient)
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?
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.
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?
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 =)
I wonder why it isn't like this from the beginning... Geniuine question, not a rhetorical one. I'm curious.
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.