Commit 6431f5fc authored by Tim Neutkens's avatar Tim Neutkens Committed by Guillermo Rauch

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
parent ddd93e98
...@@ -11,8 +11,16 @@ export default class Link extends Component { ...@@ -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 { ...@@ -54,28 +62,24 @@ export default class Link extends Component {
} }
render () { render () {
const children = Children.map(this.props.children, (child) => { let { children } = this.props
const props = { // Deprecated. Warning shown by propType check. If the childen provided is a string (<Link>example</Link>) we wrap it in an <a> tag
onClick: this.linkClicked if (typeof children === 'string') {
} children = <a>{children}</a>
}
const isAnchor = child && child.type === 'a'
// if child does not specify a href, specify it // This will return the first child, if multiple are provided it will throw an error
// so that repetition is not needed by the user const child = Children.only(children)
if (!isAnchor || !('href' in child.props)) { const props = {
props.href = this.props.as || this.props.href onClick: this.linkClicked
} }
if (isAnchor) { // 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
return React.cloneElement(child, props) if (child.type === 'a' && !('href' in child.props)) {
} else { props.href = this.props.as || this.props.href
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)
} }
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment