Skip to content

Commit

Permalink
feat(dropdown): add outside click handler
Browse files Browse the repository at this point in the history
listen for outside click to close the dropdown

BREAKING CHANGE: You don't need to provide an outside click handler to close the dropdown anymore as
it's now done internally calling the passed onClose prop
  • Loading branch information
estevanmaito committed Jul 10, 2020
1 parent 2769803 commit c316cd4
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 2 deletions.
26 changes: 26 additions & 0 deletions __tests__/Dropdown.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,32 @@ describe('Dropdown', () => {
expect(onClose).toHaveBeenCalled()
})

it('should close dropdown when clicking outside it', () => {
const map = {}
document.addEventListener = jest.fn((e, cb) => {
map[e] = cb
})
const onClose = jest.fn()
mount(<Dropdown isOpen={true} onClose={onClose} />)

map.click({ target: document.body })

expect(onClose).toHaveBeenCalled()
})

it('should not close dropdown when clicking inside it', () => {
const map = {}
document.addEventListener = jest.fn((e, cb) => {
map[e] = cb
})
const onClose = jest.fn()
const wrapper = mount(<Dropdown isOpen={true} onClose={onClose} />)

map.click({ target: wrapper.find('ul').getDOMNode() })

expect(onClose).not.toHaveBeenCalled()
})

it('should not call onClose when other key than Esc is pressed', () => {
const map = {}
document.addEventListener = jest.fn((e, cb) => {
Expand Down
13 changes: 11 additions & 2 deletions src/Dropdown.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React, { useEffect, useContext } from 'react'
import React, { useEffect, useContext, useRef } from 'react'
import classNames from 'classnames'
import PropTypes from 'prop-types'
import { ThemeContext } from './context/ThemeContext'
Expand All @@ -18,9 +18,18 @@ function Dropdown({ children, onClose, isOpen, className, ...other }) {
}
}

const dropdownRef = useRef()
function handleClickOutside(e) {
if (dropdownRef.current && !dropdownRef.current.contains(e.target)) {
onClose()
}
}

useEffect(() => {
document.addEventListener('click', handleClickOutside)
document.addEventListener('keydown', handleEsc)
return () => {
document.removeEventListener('click', handleClickOutside)
document.removeEventListener('keydown', handleEsc)
}
})
Expand All @@ -36,7 +45,7 @@ function Dropdown({ children, onClose, isOpen, className, ...other }) {
>
<div>
<FocusLock returnFocus>
<ul className={cls} aria-label="submenu" {...other}>
<ul className={cls} ref={dropdownRef} aria-label="submenu" {...other}>
{children}
</ul>
</FocusLock>
Expand Down

0 comments on commit c316cd4

Please sign in to comment.