@@ -5,23 +5,60 @@ import PropTypes from 'prop-types';
5
5
/**
6
6
* Helper for switching between <button>, <a>, and <Link>
7
7
*/
8
- const ButtonOrLink = ( { href, children, ...props } ) => {
9
- if ( href ) {
10
- if ( href . startsWith ( 'http' ) ) {
8
+
9
+ const ButtonOrLink = React . forwardRef (
10
+ ( { href, children, isDisabled, onClick, ...props } , ref ) => {
11
+ const handleClick = ( e ) => {
12
+ if ( isDisabled ) {
13
+ e . preventDefault ( ) ;
14
+ e . stopPropagation ( ) ;
15
+ return ;
16
+ }
17
+ if ( onClick ) {
18
+ onClick ( e ) ;
19
+ }
20
+ } ;
21
+
22
+ if ( href ) {
23
+ if ( href . startsWith ( 'http' ) ) {
24
+ return (
25
+ < a
26
+ ref = { ref }
27
+ href = { href }
28
+ target = "_blank"
29
+ rel = "noopener noreferrer"
30
+ aria-disabled = { isDisabled }
31
+ { ...props }
32
+ onClick = { handleClick }
33
+ >
34
+ { children }
35
+ </ a >
36
+ ) ;
37
+ }
11
38
return (
12
- < a href = { href } target = "_blank" rel = "noopener noreferrer" { ...props } >
39
+ < Link
40
+ ref = { ref }
41
+ to = { href }
42
+ aria-disabled = { isDisabled }
43
+ { ...props }
44
+ onClick = { handleClick }
45
+ >
13
46
{ children }
14
- </ a >
47
+ </ Link >
15
48
) ;
16
49
}
17
50
return (
18
- < Link to = { href } { ...props } >
51
+ < button
52
+ ref = { ref }
53
+ aria-disabled = { isDisabled }
54
+ { ...props }
55
+ onClick = { handleClick }
56
+ >
19
57
{ children }
20
- </ Link >
58
+ </ button >
21
59
) ;
22
60
}
23
- return < button { ...props } > { children } </ button > ;
24
- } ;
61
+ ) ;
25
62
26
63
/**
27
64
* Accepts all the props of an HTML <a> or <button> tag.
@@ -34,15 +71,19 @@ ButtonOrLink.propTypes = {
34
71
* External links should start with 'http' or 'https' and will open in a new window.
35
72
*/
36
73
href : PropTypes . string ,
74
+ isDisabled : PropTypes . bool ,
37
75
/**
38
76
* Content of the button/link.
39
77
* Can be either a string or a complex element.
40
78
*/
41
- children : PropTypes . node . isRequired
79
+ children : PropTypes . node . isRequired ,
80
+ onClick : PropTypes . func
42
81
} ;
43
82
44
83
ButtonOrLink . defaultProps = {
45
- href : null
84
+ href : null ,
85
+ isDisabled : false ,
86
+ onClick : null
46
87
} ;
47
88
48
89
export default ButtonOrLink ;
0 commit comments