@@ -11,8 +11,16 @@ export default class Link extends Component {
11
11
12
12
static propTypes = {
13
13
children : PropTypes . oneOfType ( [
14
- PropTypes . string ,
15
- PropTypes . element
14
+ PropTypes . element ,
15
+ ( props , propName ) => {
16
+ const value = props [ propName ]
17
+
18
+ if ( typeof value === 'string' ) {
19
+ warnLink ( `Warning: You're using a string directly inside <Link>. This usage has been deprecated. Please add an <a> tag as child of <Link>` )
20
+ }
21
+
22
+ return null
23
+ }
16
24
] ) . isRequired
17
25
}
18
26
@@ -54,28 +62,24 @@ export default class Link extends Component {
54
62
}
55
63
56
64
render ( ) {
57
- const children = Children . map ( this . props . children , ( child ) => {
58
- const props = {
59
- onClick : this . linkClicked
60
- }
61
-
62
- const isAnchor = child && child . type === 'a'
65
+ let { children } = this . props
66
+ // Deprecated. Warning shown by propType check. If the childen provided is a string (<Link>example</Link>) we wrap it in an <a> tag
67
+ if ( typeof children === 'string' ) {
68
+ children = < a > { children } </ a >
69
+ }
63
70
64
- // if child does not specify a href, specify it
65
- // so that repetition is not needed by the user
66
- if ( ! isAnchor || ! ( 'href' in child . props ) ) {
67
- props . href = this . props . as || this . props . href
68
- }
71
+ // This will return the first child, if multiple are provided it will throw an error
72
+ const child = Children . only ( children )
73
+ const props = {
74
+ onClick : this . linkClicked
75
+ }
69
76
70
- if ( isAnchor ) {
71
- return React . cloneElement ( child , props )
72
- } else {
73
- warnLink ( `Warning: Every Link must be the parent of an anchor, this pattern is deprecated. Please add an anchor inside the <Link>.` )
74
- return < a { ...props } > { child } </ a >
75
- }
76
- } )
77
+ // If child is an <a> tag and doesn't have a href attribute we specify it so that repetition is not needed by the user
78
+ if ( child . type === 'a' && ! ( 'href' in child . props ) ) {
79
+ props . href = this . props . as || this . props . href
80
+ }
77
81
78
- return children [ 0 ]
82
+ return React . cloneElement ( child , props )
79
83
}
80
84
}
81
85
0 commit comments