diff --git a/src/component/escapable.js b/src/component/escapable.js new file mode 100644 index 000000000..e6630b14e --- /dev/null +++ b/src/component/escapable.js @@ -0,0 +1,33 @@ +import { Component } from 'react'; +import PropTypes from 'prop-types'; + +class Escapable extends Component { + constructor(props) { + super(props); + this.handleKeyDown = this.handleKeyDown.bind(this); + } + + componentDidMount() { + if (typeof document !== 'undefined') { + document.addEventListener('keydown', this.handleKeyDown); + } + } + + componentWillUnmount() { + if (typeof document !== 'undefined') { + document.removeEventListener('keydown', this.handleKeyDown); + } + } + + handleKeyDown(event) { + if (event.keyCode === 27) { + this.props.onClose(); + } + } +} + +Escapable.propTypes = { + onClose: PropTypes.func.isRequired, +}; + +export default Escapable; diff --git a/src/component/modal.js b/src/component/modal.js index 01a906235..0a110c00a 100644 --- a/src/component/modal.js +++ b/src/component/modal.js @@ -1,9 +1,10 @@ import React from 'react'; import { View, ViewPropTypes, StyleSheet } from 'react-native'; import PropTypes from 'prop-types'; -import { Button } from '../../src/component/button'; +import { Button } from './button'; import { H4Text } from './text'; import Icon from './icon'; +import Escapable from './escapable'; import { color } from './style'; const styles = StyleSheet.create({ @@ -34,15 +35,20 @@ const styles = StyleSheet.create({ }, }); -const Modal = ({ title = '', onClose, children, style }) => ( - - {title.toUpperCase()} - - {children} - -); +class Modal extends Escapable { + render() { + const { title = '', style, onClose, children } = this.props; + return ( + + {title.toUpperCase()} + + {children} + + ); + } +} Modal.propTypes = { title: PropTypes.string.isRequired,