Make space and enter actually work if focused

If the delete button is the current active element (e.g. focused by tab) make hitting ‘space’ or ‘Enter’ do the actual delete.
This commit is contained in:
Chris Garrity committed 2019-07-26 09:37:39 -04:00
1 parent cd7b5d93ee
commit 1b4b50b09a
1 file changed
+48 -21
+48 -21
View File
@@ -1,31 +1,58 @@
import PropTypes from 'prop-types';
import React from 'react';
import bindAll from 'lodash.bindall';
import classNames from 'classnames';
import styles from './delete-button.css';
import deleteIcon from './icon--delete.svg';
const DeleteButton = props => (
<div
aria-label="Delete"
className={classNames(
styles.deleteButton,
props.className
)}
role="button"
tabIndex={props.tabIndex}
onClick={props.onClick}
>
<div className={styles.deleteButtonVisible}>
<img
className={styles.deleteIcon}
draggable={false}
src={deleteIcon}
/>
</div>
</div>
);
class DeleteButton extends React.Component {
constructor (props) {
super(props);
bindAll(this, [
'handleKeyPress',
'setRef'
]);
}
componentDidMount () {
document.addEventListener('keydown', this.handleKeyPress);
}
componentWillUnmount () {
document.removeEventListener('keydown', this.handleKeyPress);
}
setRef (ref) {
this.ref = ref;
}
handleKeyPress (event) {
if (this.ref === event.currentTarget.activeElement && (event.key === 'Enter' || event.key === ' ')) {
this.props.onClick(event);
event.preventDefault();
}
}
render () {
return (
<div
aria-label="Delete"
className={classNames(
styles.deleteButton,
this.props.className
)}
ref={this.setRef}
role="button"
tabIndex={this.props.tabIndex}
onClick={this.props.onClick}
>
<div className={styles.deleteButtonVisible}>
<img
className={styles.deleteIcon}
draggable={false}
src={deleteIcon}
/>
</div>
</div>
);
}
}
DeleteButton.propTypes = {
className: PropTypes.string,