Skip to content

Commit 6431f5f

Browse files
timneutkensrauchg
authored andcommitted
Allow any element to be rendered under Link (vercel#921)
* Allow any element to be rendered under Link * Use Children.only instead of Children.map * Remove check for multiple children since we already throw at 2+ * Clean up variables
1 parent ddd93e9 commit 6431f5f

File tree

1 file changed

+25
-21
lines changed

1 file changed

+25
-21
lines changed

lib/link.js

Lines changed: 25 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,16 @@ export default class Link extends Component {
1111

1212
static propTypes = {
1313
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+
}
1624
]).isRequired
1725
}
1826

@@ -54,28 +62,24 @@ export default class Link extends Component {
5462
}
5563

5664
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+
}
6370

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+
}
6976

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+
}
7781

78-
return children[0]
82+
return React.cloneElement(child, props)
7983
}
8084
}
8185

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy