@utilityjs/use-controlled-prop
v1.1.2
Published
A React hook that handles controllable props.
Downloads
7
Maintainers
Readme
A React hook that handles controllable props.
npm i @utilityjs/use-controlled-prop | yarn add @utilityjs/use-controlled-prop
Usage
import * as React from "react";
import useControlledProp from "@utilityjs/use-controlled-prop";
const MyComponent = (props, ref) => {
const {
onChange,
value: valueProp,
defaultValue: defaultValueProp, s
...otherProps
} = props;
const [value, setUncontrolledValue] = useControlledProp(
valueProp,
defaultValueProp,
"" // Fallback value (if both values were `undefined`)
);
return (
<Input
type="text"
value={value}
onChange={e => {
if (onChange) onChange(e);
// This line only works when the `valueProp` is not controlled
setUncontrolledValue(e.target.value);
}}
{...otherProps}
/>
);
};
API
useControlledProp(controlledValue, defaultValue, fallbackValue)
declare const useControlledProp: <T>(
controlledValueProp: T | undefined,
defaultValueProp: T | undefined,
fallbackValue: T
) => [
value: T,
setUncontrolledValue: React.Dispatch<React.SetStateAction<T>>,
isControlled: boolean
];
controlledValueProp
The value to be controlled.
defaultValueProp
The default value.
fallbackValue
The value to fallback to when controlledValue
and defaultValueProp
were undefined
.