From 0da0bb67874acefb6370e57b4be0301318d59c3b Mon Sep 17 00:00:00 2001 From: IvanDimanov Date: Sun, 24 Jan 2021 18:27:25 +0200 Subject: [PATCH] feat: add useCheckbox Co-authored-by: Ivan Dimanov --- __tests__/dataEntry.test.js | 24 +++++++++++++++++++++++- src/hooks/useCheckbox.js | 17 +++++++++++++++++ src/index.js | 2 ++ stories/dataEntry.stories.js | 18 ++++++++++++++++++ 4 files changed, 60 insertions(+), 1 deletion(-) create mode 100644 src/hooks/useCheckbox.js diff --git a/__tests__/dataEntry.test.js b/__tests__/dataEntry.test.js index d45517a..0f6dc52 100644 --- a/__tests__/dataEntry.test.js +++ b/__tests__/dataEntry.test.js @@ -3,7 +3,9 @@ import React from 'react' import { render, fireEvent, } from 'react-testing-library' -import { useField } from '../src/index' +import { + useField, useCheckbox, +} from '../src/index' test('useField', () => { const Input = () => { @@ -24,3 +26,23 @@ test('useField', () => { fireEvent.click(getByText('reset')) expect(container.firstChild.firstChild.textContent).toBe('Type Here...') }) + +test('useCheckbox', () => { + const Input = () => { + const { checked, bind, reset } = useCheckbox(false) + + return ( +
+ {String(checked)} + + +
+ ) + } + const { container, getByText } = render() + expect(container.firstChild.firstChild.textContent).toBe('false') + fireEvent.click(container.firstChild.lastChild) + expect(container.firstChild.firstChild.textContent).toBe('true') + fireEvent.click(getByText('reset')) + expect(container.firstChild.firstChild.textContent).toBe('false') +}) diff --git a/src/hooks/useCheckbox.js b/src/hooks/useCheckbox.js new file mode 100644 index 0000000..d7681ec --- /dev/null +++ b/src/hooks/useCheckbox.js @@ -0,0 +1,17 @@ +import { useState } from 'react' + +const useCheckbox = (initial) => { + const [checked, set] = useState(initial) + + return { + checked, + set, + reset: () => set(initial), + bind: { + checked, + onChange: e => set(e.target.checked), + }, + } +} + +export default useCheckbox diff --git a/src/index.js b/src/index.js index 73059d3..da3aa54 100644 --- a/src/index.js +++ b/src/index.js @@ -16,6 +16,8 @@ export { default as useMap } from './hooks/useMap' export { default as useField } from './hooks/useField' +export { default as useCheckbox } from './hooks/useCheckbox' + export { default as useFetch } from './hooks/useFetch' export { default as useMergeState } from './hooks/useMergeState' diff --git a/stories/dataEntry.stories.js b/stories/dataEntry.stories.js index 3d94d90..ce48ed2 100644 --- a/stories/dataEntry.stories.js +++ b/stories/dataEntry.stories.js @@ -36,3 +36,21 @@ storiesOf(section('useField'), module) ) `) + +storiesOf(section('useCheckbox'), module) + .addLiveSource('demo', ` + const Checkbox = () => { + const { checked, bind } = useCheckbox(false) + + return ( +
+ is checked: + {String(checked)} + +
+ ) + } + return ( + + ) +`)