From f4fd748d453c73f396064148fd773b42f3355782 Mon Sep 17 00:00:00 2001 From: streamich Date: Thu, 28 Mar 2019 19:52:33 +0100 Subject: [PATCH] =?UTF-8?q?feat:=20=F0=9F=8E=B8=20add=20createRenderProp?= =?UTF-8?q?=20function=20for=20creating=20render-props?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/useKey.md | 8 ++++++++ src/comps/UseKey.tsx | 6 ++++++ src/comps/__stories__/UseKey.story.tsx | 11 +++++++++++ src/util/createRenderProp.ts | 13 +++++++++++++ 4 files changed, 38 insertions(+) create mode 100644 src/comps/UseKey.tsx create mode 100644 src/comps/__stories__/UseKey.story.tsx create mode 100644 src/util/createRenderProp.ts diff --git a/docs/useKey.md b/docs/useKey.md index 36661708e7..e00df3d57f 100644 --- a/docs/useKey.md +++ b/docs/useKey.md @@ -20,6 +20,14 @@ const Demo = () => { }; ``` +Or as render-prop: + +```jsx +import UseKey from 'react-use/lib/comps/UseKey'; + + alert('"a" key pressed!')} /> +``` + ## Reference diff --git a/src/comps/UseKey.tsx b/src/comps/UseKey.tsx new file mode 100644 index 0000000000..28c45b7bf8 --- /dev/null +++ b/src/comps/UseKey.tsx @@ -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; diff --git a/src/comps/__stories__/UseKey.story.tsx b/src/comps/__stories__/UseKey.story.tsx new file mode 100644 index 0000000000..7404eeb236 --- /dev/null +++ b/src/comps/__stories__/UseKey.story.tsx @@ -0,0 +1,11 @@ +import {storiesOf} from '@storybook/react'; +import * as React from 'react'; +import UseKey from '../UseKey'; + +storiesOf('Components|', module) + .add('Demo', () => +
+ Press "q" key! + alert('Q pressed!')} /> +
+ ) diff --git a/src/util/createRenderProp.ts b/src/util/createRenderProp.ts new file mode 100644 index 0000000000..c1e0985e61 --- /dev/null +++ b/src/util/createRenderProp.ts @@ -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;