@yookue/react-condition
Version:
Render components conditionally for react
47 lines • 2.02 kB
JavaScript
import React from 'react';
export var Switch = function Switch(props) {
var _caseValue;
if (!(props !== null && props !== void 0 && props.children)) {
return undefined;
}
if ((props === null || props === void 0 ? void 0 : props.validation) !== false) {
var caseCount = 0,
defaultCount = 0;
React.Children.forEach(props.children, function (item) {
var childType = item === null || item === void 0 ? void 0 : item.type;
if (childType === Switch.Case) {
caseCount++;
}
if (childType === Switch.Default) {
defaultCount++;
}
});
if (caseCount === 0 && defaultCount === 0) {
throw SyntaxError("[Switch] must has any statements of 'Switch.Case/Switch.Default' at least!");
}
if (defaultCount > 1) {
throw SyntaxError("Statement of 'Switch.Default' for [Switch] must be a single one at most!");
}
}
var caseValue = undefined,
defaultValue = undefined;
React.Children.forEach(props.children, function (item) {
var _item$props;
var childType = item === null || item === void 0 ? void 0 : item.type;
if (childType === Switch.Case && (_item$props = item.props) !== null && _item$props !== void 0 && _item$props.condition) {
var _item$props2;
caseValue = (_item$props2 = item.props) === null || _item$props2 === void 0 ? void 0 : _item$props2.children;
}
if (childType === Switch.Default) {
var _item$props3;
defaultValue = (_item$props3 = item.props) === null || _item$props3 === void 0 ? void 0 : _item$props3.children;
}
});
return (_caseValue = caseValue) !== null && _caseValue !== void 0 ? _caseValue : defaultValue;
};
Switch.Case = function (props) {
return !props.condition ? undefined : props !== null && props !== void 0 && props.render ? props.render() : props.children;
};
Switch.Default = function (props) {
return props !== null && props !== void 0 && props.render ? props.render() : props === null || props === void 0 ? void 0 : props.children;
};