Skip to content

Commit

Permalink
feat: add useCheckbox
Browse files Browse the repository at this point in the history
Co-authored-by: Ivan Dimanov <[email protected]>
  • Loading branch information
IvanDimanov and IvanDimanovGearLaunch authored Jan 24, 2021
1 parent 409b054 commit 0da0bb6
Show file tree
Hide file tree
Showing 4 changed files with 60 additions and 1 deletion.
24 changes: 23 additions & 1 deletion __tests__/dataEntry.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = () => {
Expand All @@ -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 (
<div>
<span>{String(checked)}</span>
<button onClick={reset}>reset</button>
<input type="checkbox" {...bind} />
</div>
)
}
const { container, getByText } = render(<Input />)
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')
})
17 changes: 17 additions & 0 deletions src/hooks/useCheckbox.js
Original file line number Diff line number Diff line change
@@ -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
2 changes: 2 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
18 changes: 18 additions & 0 deletions stories/dataEntry.stories.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,3 +36,21 @@ storiesOf(section('useField'), module)
)
`)

storiesOf(section('useCheckbox'), module)
.addLiveSource('demo', `
const Checkbox = () => {
const { checked, bind } = useCheckbox(false)
return (
<div>
is checked:
{String(checked)}
<input type="checkbox" {...bind} />
</div>
)
}
return (
<Checkbox />
)
`)

0 comments on commit 0da0bb6

Please sign in to comment.