Skip to content

Commit

Permalink
docs: update docs
Browse files Browse the repository at this point in the history
  • Loading branch information
wujihua committed Dec 26, 2022
1 parent 56f7739 commit e7b5ac4
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 5 deletions.
48 changes: 47 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,49 @@
# use-controlled

Easily manage controlled/uncontrolled property values of your components.
🆒 Easily manage controlled/uncontrolled property values of your components.

<br />
<div align="center">
<pre>pnpm add use-controlled</pre>
</div>
<br />
<br />

## Usage

```ts
import * as React from 'react'
import { useControlled } from 'use-controlled'

type InputValue = string | number

interface InputProps {
defaultValue: InputValue
value: InputValue
onChange: (value: InputValue, event?: React.ChangeEvent<HTMLInputElement>) => void
// ...other properties
}

const Input = React.forwardRef<HTMLInputElement, InputProps>((props, ref) => {

const [innerValue, setInnerValue] = useControlled(props, 'value', props.onChange)

const handleChange = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
setInnerValue(event.target.value, event)
},
[],
)

return (
<input
ref={ref}
value={innerValue || props.defaultValue}
onChange={handleChange}
/>
)
})

export default Input

```
6 changes: 2 additions & 4 deletions packages/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export interface ChangeHandler<T, A extends any[]> {

const noop = () => {}

const useControlled = <T, A extends any[]>(
export const useControlled = <T, A extends any[]>(
props: Record<string, any> = {},
valueKey: string,
onChange: ChangeHandler<T, A>
Expand All @@ -26,6 +26,4 @@ const useControlled = <T, A extends any[]>(
onChange?.(newValue, ...args)
},
]
}

export default useControlled
}

0 comments on commit e7b5ac4

Please sign in to comment.