optimizely-oui
Version:
Optimizely's Component Library.
54 lines (46 loc) • 2.43 kB
JavaScript
function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); }
function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); }
function _iterableToArrayLimit(arr, i) { if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) { return; } var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }
function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }
import { useState } from "react";
import PropTypes from "prop-types";
/**
* @name StoryStateWrapper
* @description
* This HOC allows us to use React's useState hook within our Story (source: https://levelup.gitconnected.com/adding-state-to-storybook-in-react-c6744fda25b4).
* The initialValue or initialValues props are mutually exclusive.
* The prop initialValue can be used if only one piece of state is needed.
* Add an array of initialValues to return an array of state / setter arrays.
*
* @param {Object} props props from child component to be decorated
* @param {*} initialValue (optional)
* For uses where only one state / setter is needed, sets initial state value.
* @param {Array} initialValues (optional)
* For uses where multiple state / setters are needed,
* sets initial state values.
*
* @returns {ReactElement} Provided component decorated with state and setters
*/
export function StoryStateWrapper(_ref) {
var children = _ref.children,
initialValue = _ref.initialValue,
initialValues = _ref.initialValues;
if (Array.isArray(initialValues)) {
return children(initialValues.map(function (value) {
return useState(initialValue);
}));
}
var _useState = useState(initialValue),
_useState2 = _slicedToArray(_useState, 2),
state = _useState2[0],
setState = _useState2[1];
return children(state, setState);
}
StoryStateWrapper.propTypes = {
initialValue: PropTypes.any,
initialValues: PropTypes.arrayOf(PropTypes.any)
};
StoryStateWrapper.defaultProps = {
initialValue: null,
initialValues: null
};