UNPKG

@awsui/components-react

Version:

AWS UI is a collection of [React](https://reactjs.org/) components that help create intuitive, responsive, and accessible user experiences for web applications. It is developed by Amazon Web Services (AWS). This work is available under the terms of the [A

39 lines (38 loc) 2.28 kB
import * as React from 'react'; import { isDevelopment } from '../../is-development'; import { warnOnce } from '../../logging'; export function useControllable(controlledValue, handler, defaultValue, _a) { var componentName = _a.componentName, changeHandler = _a.changeHandler, controlledProp = _a.controlledProp; var isControlled = React.useState(controlledValue !== undefined)[0]; if (isDevelopment) { React.useEffect(function () { if (isControlled && handler === undefined) { warnOnce(componentName, "You provided a `" + controlledProp + "` prop without an `" + changeHandler + "` handler. This will render a non-interactive component."); } }, [handler, isControlled, componentName, changeHandler, controlledProp]); React.useEffect(function () { var isControlledNow = controlledValue !== undefined; if (isControlled !== isControlledNow) { var initialMode = isControlled ? 'controlled' : 'uncontrolled'; var modeNow = isControlledNow ? 'controlled' : 'uncontrolled'; warnOnce(componentName, "A component tried to change " + initialMode + " '" + controlledProp + "' property to be " + modeNow + ". " + ("This is not supported. Properties should not switch from " + initialMode + " to " + modeNow + " (or vice versa). ") + "Decide between using a controlled or uncontrolled mode for the lifetime of the component. " + "More info: https://fb.me/react-controlled-components"); } }, [isControlled, controlledProp, componentName, controlledValue]); } var _b = React.useState(defaultValue), valueState = _b[0], setValue = _b[1]; var _c = React.useState(false), valueHasBeenSet = _c[0], setValueHasBeenSet = _c[1]; var currentUncontrolledValue = valueHasBeenSet ? valueState : defaultValue; var setUncontrolledValue = React.useCallback(function (newValue) { setValue(newValue); setValueHasBeenSet(true); }, [setValue, setValueHasBeenSet]); if (isControlled) { return [controlledValue, function () { return void 0; }]; } else { return [currentUncontrolledValue, setUncontrolledValue]; } }