Files
react/components/use-input/use-input.tsx
witt 563fb67c72 fix: migrate the hooks file path in esm (#603)
* fix: move use-input to root-layer

* chore: move all hooks to root-layer

* test: fix test utils path for hooks
2021-08-13 18:00:52 +08:00

41 lines
969 B
TypeScript

import React, { Dispatch, MutableRefObject, SetStateAction } from 'react'
import useCurrentState from '../utils/use-current-state'
export type BindingsChangeTarget =
| React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>
| string
const useInput = (
initialValue: string,
): {
state: string
setState: Dispatch<SetStateAction<string>>
currentRef: MutableRefObject<string>
reset: () => void
bindings: {
value: string
onChange: (event: BindingsChangeTarget) => void
}
} => {
const [state, setState, currentRef] = useCurrentState<string>(initialValue)
return {
state,
setState,
currentRef,
reset: () => setState(initialValue),
bindings: {
value: state,
onChange: (event: BindingsChangeTarget) => {
if (typeof event === 'object' && event.target) {
setState(event.target.value)
} else {
setState(event as string)
}
},
},
}
}
export default useInput