Pomax / react-onclickoutside

An onClickOutside wrapper for React components
MIT License
1.83k stars 187 forks source link

WrapperComponent for React Hooks #316

Open jmattheis opened 5 years ago

jmattheis commented 5 years ago

The current recommendation for functional components is adding a static handler function. This solution doesn't work when the functional component is rendered multiple times.

It should be possible to add a compontent which accepts a callback that is called every time the outside was clicked.

import * as React from "react";
import onClickOutside from "react-onclickoutside";

interface OnClickOutsideProps {
    onClickOutside: (event) => void;
}

export class XOutsideClickHandler extends React.Component<OnClickOutsideProps>{
    public handleClickOutside = (event) => this.props.onClickOutside(event);
    public render = () => this.props.children;
}

export const OutsideClickHandler: React.ComponentClass<OnClickOutsideProps> = onClickOutside(XOutsideClickHandler);

It could be used with React hooks like this:

export const Menu = () => {
    const [open, setOpen] = React.useState(false);
    return (
        <OutsideClickHandler onClickOutside={() => setOpen(false)}>
            <input type="button" onClick={() => setOpen(true)}/>
            {`open = ${open}`}
        </OutsideClickHandler>
    );
};

Could this be added to this repository?