mirror of
https://github.com/terribleplan/next.js.git
synced 2024-01-19 02:48:18 +00:00
Allow any element to be rendered under Link (#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
This commit is contained in:
parent
ddd93e9865
commit
6431f5fce2
36
lib/link.js
36
lib/link.js
|
@ -11,8 +11,16 @@ export default class Link extends Component {
|
||||||
|
|
||||||
static propTypes = {
|
static propTypes = {
|
||||||
children: PropTypes.oneOfType([
|
children: PropTypes.oneOfType([
|
||||||
PropTypes.string,
|
PropTypes.element,
|
||||||
PropTypes.element
|
(props, propName) => {
|
||||||
|
const value = props[propName]
|
||||||
|
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
warnLink(`Warning: You're using a string directly inside <Link>. This usage has been deprecated. Please add an <a> tag as child of <Link>`)
|
||||||
|
}
|
||||||
|
|
||||||
|
return null
|
||||||
|
}
|
||||||
]).isRequired
|
]).isRequired
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -54,28 +62,24 @@ export default class Link extends Component {
|
||||||
}
|
}
|
||||||
|
|
||||||
render () {
|
render () {
|
||||||
const children = Children.map(this.props.children, (child) => {
|
let { children } = this.props
|
||||||
|
// Deprecated. Warning shown by propType check. If the childen provided is a string (<Link>example</Link>) we wrap it in an <a> tag
|
||||||
|
if (typeof children === 'string') {
|
||||||
|
children = <a>{children}</a>
|
||||||
|
}
|
||||||
|
|
||||||
|
// This will return the first child, if multiple are provided it will throw an error
|
||||||
|
const child = Children.only(children)
|
||||||
const props = {
|
const props = {
|
||||||
onClick: this.linkClicked
|
onClick: this.linkClicked
|
||||||
}
|
}
|
||||||
|
|
||||||
const isAnchor = child && child.type === 'a'
|
// 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
|
||||||
|
if (child.type === 'a' && !('href' in child.props)) {
|
||||||
// if child does not specify a href, specify it
|
|
||||||
// so that repetition is not needed by the user
|
|
||||||
if (!isAnchor || !('href' in child.props)) {
|
|
||||||
props.href = this.props.as || this.props.href
|
props.href = this.props.as || this.props.href
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isAnchor) {
|
|
||||||
return React.cloneElement(child, props)
|
return React.cloneElement(child, props)
|
||||||
} else {
|
|
||||||
warnLink(`Warning: Every Link must be the parent of an anchor, this pattern is deprecated. Please add an anchor inside the <Link>.`)
|
|
||||||
return <a {...props}>{child}</a>
|
|
||||||
}
|
|
||||||
})
|
|
||||||
|
|
||||||
return children[0]
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Reference in a new issue