Skip to content

Commit

Permalink
Allow any element to be rendered under Link (#921)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
timneutkens authored and rauchg committed Feb 3, 2017
1 parent ddd93e9 commit 6431f5f
Showing 1 changed file with 25 additions and 21 deletions.
46 changes: 25 additions & 21 deletions lib/link.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
}

Expand Down Expand Up @@ -54,28 +62,24 @@ export default class Link extends Component {
}

render () {
const children = Children.map(this.props.children, (child) => {
const props = {
onClick: this.linkClicked
}

const isAnchor = child && child.type === 'a'
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>
}

// 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
}
// 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 (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>
}
})
// 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
}

return children[0]
return React.cloneElement(child, props)
}
}

Expand Down

0 comments on commit 6431f5f

Please sign in to comment.