UNPKG

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