Skip to content

It allows you to perform your operations in locations other than the place marked with ref.

License

Notifications You must be signed in to change notification settings

omtanke/react-use-event-outside

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

45 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

react-use-event-outside

Installation

Install with Yarn:

yarn add @omtanke/react-use-event-outside

Or with NPM:

npm i @omtanke/react-use-event-outside

Import into your component like so:

import useEventOutside from '@omtanke/react-use-event-outside';

Usage

useEventOutside(REF, EVENT_NAME, FUNCTION);

REF: Outside which element you want to trigger.

EVENT_NAME: You want to listen to the event (Ex: 'mousedown', 'touchstart', etc.).

FUNCTION: The function you want to run when triggered.

Example

CodeSandbox

or

const App = () => {
    const ref = useRef(null);
    const [isOpen, setIsOpen] = useState(false);
    
    const closeMenu = useCallback(() => {
        setIsOpen(false);
    }, []);
    
    useEventOutside(ref, 'mousedown', closeMenu);
    
    return (
        <nav className="dropdown" ref={ref}>
            <button onClick={() => setIsOpen(!isOpen)}>Toggle</button>
            {isOpen &&
                <ul className='dropdown-menu'>
                    <li className='dropdown-item'>Item</li>
                    <li className='dropdown-item'>Item</li>
                </ul>    
            }
        </nav>
    );
};

About

It allows you to perform your operations in locations other than the place marked with ref.

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages