Skip to content

Commit

Permalink
feat(Dropdown): close Dropdown when ESC is pressed (carbon-design-sys…
Browse files Browse the repository at this point in the history
…tem#788)

* feat(Dropdown): close Dropdown when ESC is pressed

* feat(Dropdown): close Dropdown when ESC is pressed

* feat(Dropdown): close Dropdown when ESC is pressed

* feat(Dropdown): close Dropdown when ESC is pressed
  • Loading branch information
rezak-otmani authored and marijohannessen committed Apr 17, 2018
1 parent c8349f4 commit b5bd74d
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
25 changes: 25 additions & 0 deletions src/components/Dropdown/Dropdown-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,7 @@ describe('Dropdown', () => {
const onClick = jest.fn();
const onOpen = jest.fn();
const onClose = jest.fn();
const handleKeydown = jest.fn();

const wrapper = mount(
<Dropdown onClick={onClick} onOpen={onOpen} onClose={onClose}>
Expand Down Expand Up @@ -145,6 +146,30 @@ describe('Dropdown', () => {
).toEqual(false);
});

it('should close when ESC is pressed', () => {
const wrapper = mount(
<Dropdown handleKeydown={handleKeydown}>
<DropdownItem
className="test-child"
itemText="test-child"
value="test-child"
/>
</Dropdown>
);

wrapper.setState({ open: true });
wrapper.mount();
dropdown.simulate('keypress', { which: 27 });
expect(
wrapper.find('.bx--dropdown').hasClass('bx--dropdown--open')
).toEqual(false);
dropdown.simulate('keypress', { which: 27 });
expect(
wrapper.find('.bx--dropdown').hasClass('bx--dropdown--open')
).toEqual(false);
wrapper.unmount();
});

it('should update data value state when child item is clicked', () => {
child.last().simulate('click');
expect(wrapper.find('.bx--dropdown').props().value).toEqual('test-child');
Expand Down
15 changes: 15 additions & 0 deletions src/components/Dropdown/Dropdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,14 @@ export default class Dropdown extends PureComponent {
}
}

componentDidMount() {
document.addEventListener('keydown', this.handleKeydown);
}

componentWillUnmount() {
document.removeEventListener('keydown', this.handleKeydown);
}

resetState(props) {
const { children, selectedText, value, defaultText, open } = props;

Expand Down Expand Up @@ -92,6 +100,13 @@ export default class Dropdown extends PureComponent {
}
};

handleKeydown = evt => {
const key = evt.keyCode || evt.which;
if (key === 27 && this.state.open) {
this.setState({ open: !this.state.open });
}
};

handleItemClick = info => {
this.props.onChange(info);
this.setState({
Expand Down

0 comments on commit b5bd74d

Please sign in to comment.