@wordpress/components
Version:
UI components for WordPress.
40 lines (37 loc) • 995 B
JavaScript
/**
* WordPress dependencies
*/
import { useState } from '@wordpress/element';
/**
* Simplified and improved implementation of useControlledState.
*
* @param props
* @param props.defaultValue
* @param props.value
* @param props.onChange
* @return The controlled value and the value setter.
*/
export function useControlledValue(_ref) {
let {
defaultValue,
onChange,
value: valueProp
} = _ref;
const hasValue = typeof valueProp !== 'undefined';
const initialValue = hasValue ? valueProp : defaultValue;
const [state, setState] = useState(initialValue);
const value = hasValue ? valueProp : state;
let setValue;
if (hasValue && typeof onChange === 'function') {
setValue = onChange;
} else if (!hasValue && typeof onChange === 'function') {
setValue = nextValue => {
onChange(nextValue);
setState(nextValue);
};
} else {
setValue = setState;
}
return [value, setValue];
}
//# sourceMappingURL=use-controlled-value.js.map