Skip to content

Commit

Permalink
feat: 🎸 add createRenderProp function for creating render-props
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Mar 28, 2019
1 parent 565d2e9 commit f4fd748
Show file tree
Hide file tree
Showing 4 changed files with 38 additions and 0 deletions.
8 changes: 8 additions & 0 deletions docs/useKey.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,14 @@ const Demo = () => {
};
```

Or as render-prop:

```jsx
import UseKey from 'react-use/lib/comps/UseKey';

<UseKey filter='a' fn={() => alert('"a" key pressed!')} />
```


## Reference

Expand Down
6 changes: 6 additions & 0 deletions src/comps/UseKey.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import createRenderProp from '../util/createRenderProp';
import useKey from '../useKey';

const UseKey = createRenderProp(useKey, ({filter, fn, deps, ...rest}) => [filter, fn, rest, deps]);

export default UseKey;
11 changes: 11 additions & 0 deletions src/comps/__stories__/UseKey.story.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import {storiesOf} from '@storybook/react';
import * as React from 'react';
import UseKey from '../UseKey';

storiesOf('Components|<UseKey>', module)
.add('Demo', () =>
<div>
Press "q" key!
<UseKey filter='q' fn={() => alert('Q pressed!')} />
</div>
)
13 changes: 13 additions & 0 deletions src/util/createRenderProp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
const defaultMapPropsToArgs = props => [props];

const createRenderProp = (hook, mapPropsToArgs = defaultMapPropsToArgs) => {
const RenderProp = (props) => {
const state = hook(...mapPropsToArgs(props));
const {children, render = children} = props;
return render ? render(state) || null : null;
};

return RenderProp;
};

export default createRenderProp;

0 comments on commit f4fd748

Please sign in to comment.