@utilityjs/use-controlled-prop
TypeScript icon, indicating that this package has built-in type declarations

1.1.2 • Public • Published

useControlledProp

A React hook that handles controllable props.

license npm latest package npm downloads types

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.

Package Sidebar

Install

npm i @utilityjs/use-controlled-prop

Weekly Downloads

10

Version

1.1.2

License

MIT

Unpacked Size

11.7 kB

Total Files

8

Last publish

Collaborators

  • mimshins