UNPKG

react-test-attributes

Version:

React library to add data-* attributes to DOM elements.

45 lines (34 loc) 1.38 kB
import { createContext, useContext, createElement, Fragment, Children, cloneElement } from 'react'; import { __rest } from 'tslib'; import { isFragment, isElement } from 'react-is'; var TestConfigContext = /*#__PURE__*/ createContext({}); TestConfigContext.displayName = 'TestAttributesConfigContext'; var defaultConfig = { suffix: 'testid', enableInProductionMode: false }; var TestAttribute = function TestAttribute(_a) { var children = _a.children, props = __rest(_a, ["children"]); var isProduction = process.env.NODE_ENV === 'production'; var config = Object.assign({}, defaultConfig, useContext(TestConfigContext), props); function withTestAttribute(nodes) { var _a, _b; var node = Children.only(nodes); var testAttributeName = "data-" + config.suffix; if (isFragment(node)) { return createElement('div', (_a = {}, _a[testAttributeName] = config.id, _a), node); } else if (isElement(node)) { return cloneElement(node, (_b = {}, _b[testAttributeName] = config.id, _b)); } else { return node; } } return createElement(Fragment, null, !config.enableInProductionMode && isProduction ? children : withTestAttribute(children)); }; var TestAttributesConfig = TestConfigContext.Provider; export default TestAttribute; export { TestAttributesConfig }; //# sourceMappingURL=react-test-attributes.esm.js.map