-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathButtonOrLink.jsx
89 lines (83 loc) · 1.87 KB
/
ButtonOrLink.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
import React from 'react';
import { Link } from 'react-router-dom';
import PropTypes from 'prop-types';
/**
* Helper for switching between <button>, <a>, and <Link>
*/
const ButtonOrLink = React.forwardRef(
({ href, children, isDisabled, onClick, ...props }, ref) => {
const handleClick = (e) => {
if (isDisabled) {
e.preventDefault();
e.stopPropagation();
return;
}
if (onClick) {
onClick(e);
}
};
if (href) {
if (href.startsWith('http')) {
return (
<a
ref={ref}
href={href}
target="_blank"
rel="noopener noreferrer"
aria-disabled={isDisabled}
{...props}
onClick={handleClick}
>
{children}
</a>
);
}
return (
<Link
ref={ref}
to={href}
aria-disabled={isDisabled}
{...props}
onClick={handleClick}
>
{children}
</Link>
);
}
return (
<button
ref={ref}
aria-disabled={isDisabled}
{...props}
onClick={handleClick}
>
{children}
</button>
);
}
);
/**
* Accepts all the props of an HTML <a> or <button> tag.
*/
ButtonOrLink.propTypes = {
/**
* If providing an href, will render as a link instead of a button.
* Can be internal or external.
* Internal links will use react-router.
* External links should start with 'http' or 'https' and will open in a new window.
*/
href: PropTypes.string,
isDisabled: PropTypes.bool,
/**
* Content of the button/link.
* Can be either a string or a complex element.
*/
children: PropTypes.node.isRequired,
onClick: PropTypes.func
};
ButtonOrLink.defaultProps = {
href: null,
isDisabled: false,
onClick: null
};
export default ButtonOrLink;