1
0
Fork 0
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:
Tim Neutkens 2017-02-03 21:27:12 +01:00 committed by Guillermo Rauch
parent ddd93e9865
commit 6431f5fce2

View file

@ -11,8 +11,16 @@ export default class Link extends Component {
static propTypes = {
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
}
@ -54,28 +62,24 @@ export default class Link extends Component {
}
render () {
const children = Children.map(this.props.children, (child) => {
const props = {
onClick: this.linkClicked
}
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>
}
const isAnchor = child && child.type === 'a'
// This will return the first child, if multiple are provided it will throw an error
const child = Children.only(children)
const props = {
onClick: this.linkClicked
}
// 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
}
// 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)) {
props.href = this.props.as || this.props.href
}
if (isAnchor) {
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]
return React.cloneElement(child, props)
}
}