-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathButtonOrLink.jsx
59 lines (54 loc) · 1.24 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
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, ...props }, ref) => {
if (href) {
if (href.startsWith('http')) {
return (
<a
ref={ref}
href={href}
target="_blank"
rel="noopener noreferrer"
{...props}
>
{children}
</a>
);
}
return (
<Link ref={ref} to={href} {...props}>
{children}
</Link>
);
}
return (
<button ref={ref} {...props}>
{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,
/**
* Content of the button/link.
* Can be either a string or a complex element.
*/
children: PropTypes.node.isRequired
};
ButtonOrLink.defaultProps = {
href: null
};
export default ButtonOrLink;