UNPKG

2.08 kBJavaScriptView Raw
1import _extends from "@babel/runtime/helpers/esm/extends";
2import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/esm/objectWithoutPropertiesLoose";
3var _excluded = ["as", "disabled", "onKeyDown"];
4import React from 'react';
5import createChainedFunction from './createChainedFunction';
6
7function isTrivialHref(href) {
8 return !href || href.trim() === '#';
9}
10/**
11 * There are situations due to browser quirks or Bootstrap CSS where
12 * an anchor tag is needed, when semantically a button tag is the
13 * better choice. SafeAnchor ensures that when an anchor is used like a
14 * button its accessible. It also emulates input `disabled` behavior for
15 * links, which is usually desirable for Buttons, NavItems, DropdownItems, etc.
16 */
17
18
19var SafeAnchor = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
20 var _ref$as = _ref.as,
21 Component = _ref$as === void 0 ? 'a' : _ref$as,
22 disabled = _ref.disabled,
23 onKeyDown = _ref.onKeyDown,
24 props = _objectWithoutPropertiesLoose(_ref, _excluded);
25
26 var handleClick = function handleClick(event) {
27 var href = props.href,
28 onClick = props.onClick;
29
30 if (disabled || isTrivialHref(href)) {
31 event.preventDefault();
32 }
33
34 if (disabled) {
35 event.stopPropagation();
36 return;
37 }
38
39 if (onClick) {
40 onClick(event);
41 }
42 };
43
44 var handleKeyDown = function handleKeyDown(event) {
45 if (event.key === ' ') {
46 event.preventDefault();
47 handleClick(event);
48 }
49 };
50
51 if (isTrivialHref(props.href)) {
52 props.role = props.role || 'button'; // we want to make sure there is a href attribute on the node
53 // otherwise, the cursor incorrectly styled (except with role='button')
54
55 props.href = props.href || '#';
56 }
57
58 if (disabled) {
59 props.tabIndex = -1;
60 props['aria-disabled'] = true;
61 }
62
63 return /*#__PURE__*/React.createElement(Component, _extends({
64 ref: ref
65 }, props, {
66 onClick: handleClick,
67 onKeyDown: createChainedFunction(handleKeyDown, onKeyDown)
68 }));
69});
70SafeAnchor.displayName = 'SafeAnchor';
71export default SafeAnchor;
\No newline at end of file