diff --git a/packages/simple-actions/hz-pressible/package.json b/packages/simple-actions/hz-pressible/package.json new file mode 100644 index 0000000..f0d4157 --- /dev/null +++ b/packages/simple-actions/hz-pressible/package.json @@ -0,0 +1,7 @@ +{ + "name": "hz-pressible", + "version": "0.0.1", + "description": "A pressible component", + "main": "index.js", + "license": "MIT" +} diff --git a/packages/simple-actions/hz-pressible/readme.md b/packages/simple-actions/hz-pressible/readme.md new file mode 100644 index 0000000..3132b4c --- /dev/null +++ b/packages/simple-actions/hz-pressible/readme.md @@ -0,0 +1,19 @@ +A component that manages a pressed state for the children. + +```js + +const myPressible = ({pressed, setPress}) => +
setPress(true)} + onMouseUp={() => setPress(false)} + style={{ + backgroundColor: pressed ? 'pink' : 'gray', + padding: 10, + display: 'inline-block', + }} + > + Press Me +
; + + +``` diff --git a/packages/simple-actions/hz-pressible/src/index.js b/packages/simple-actions/hz-pressible/src/index.js new file mode 100644 index 0000000..2a346c8 --- /dev/null +++ b/packages/simple-actions/hz-pressible/src/index.js @@ -0,0 +1,63 @@ +// @flow +import {Component} from 'react'; + +// eslint-disable-next-line no-duplicate-imports +import type {Element} from 'react'; + +type RenderProps = {}; + +type Props = { + /** + * Something something + * @param {[type]} props [description] + * @return {[type]} [description] + */ + render: (props: RenderProps) => Element<*>, + /** + * [value description] + * @type {[type]} + */ + onPress?: (value: boolean) => void, +}; + +type State = { + pressed: boolean, +}; + +const intialState = { + pressed: false, +}; + +/** + * This is a basic pressible component + * @returns Component + */ +class Pressible extends Component { + state = {...intialState}; + + componentDidUpdate(prevProps: Props, prevState: State) { + if ( + typeof this.props.onPress === 'function' && + prevState.pressed !== this.state.pressed + ) { + this.props.onPress(this.state.pressed); + } + } + + handlePress = (pressed: boolean) => { + this.setState((state: State): ?State => { + if (pressed === state.pressed) return null; + return {...state, pressed}; + }); + }; + + render() { + return this.props.render({ + ...this.props, + ...this.state, + setPress: this.handlePress, + }); + } +} + +export default Pressible;