Skip to content

Commit

Permalink
Add Pressible component
Browse files Browse the repository at this point in the history
Ref GH-2
  • Loading branch information
elainen committed Apr 25, 2018
1 parent c673a33 commit 3a7985c
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 0 deletions.
7 changes: 7 additions & 0 deletions packages/simple-actions/hz-pressible/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"name": "hz-pressible",
"version": "0.0.1",
"description": "A pressible component",
"main": "index.js",
"license": "MIT"
}
19 changes: 19 additions & 0 deletions packages/simple-actions/hz-pressible/readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
A component that manages a pressed state for the children.

```js

const myPressible = ({pressed, setPress}) =>
<div
onMouseDown={() => setPress(true)}
onMouseUp={() => setPress(false)}
style={{
backgroundColor: pressed ? 'pink' : 'gray',
padding: 10,
display: 'inline-block',
}}
>
Press Me
</div>;

<Pressible render={myPressible} />
```
63 changes: 63 additions & 0 deletions packages/simple-actions/hz-pressible/src/index.js
Original file line number Diff line number Diff line change
@@ -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<Props, State> {
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;

0 comments on commit 3a7985c

Please sign in to comment.