1
0
Fork 0
mirror of https://github.com/terribleplan/next.js.git synced 2024-01-19 02:48:18 +00:00
next.js/lib/link.js

70 lines
1.6 KiB
JavaScript
Raw Normal View History

2016-10-06 07:07:41 +00:00
import React, { Component, PropTypes, Children } from 'react'
export default class Link extends Component {
static contextTypes = {
router: PropTypes.object
}
constructor (props) {
super(props)
this.linkClicked = this.linkClicked.bind(this)
}
linkClicked (e) {
if ('A' === e.target.nodeName &&
(e.metaKey || e.ctrlKey || e.shiftKey || 2 === e.nativeEvent.which)) {
// ignore click for new tab / new window behavior
return
}
const { href, scroll } = this.props
if (!isLocal(href)) {
// ignore click if it's outside our scope
return
}
e.preventDefault()
// straight up redirect
2016-10-08 05:12:51 +00:00
this.context.router.push(null, href)
.then((success) => {
if (!success) return
if (false !== scroll) window.scrollTo(0, 0)
})
.catch((err) => {
if (this.props.onError) this.props.onError(err)
2016-10-06 07:07:41 +00:00
})
}
render () {
const children = Children.map(this.props.children, (child) => {
const props = {
onClick: this.linkClicked
}
2016-10-08 05:12:51 +00:00
const isAnchor = child && 'a' === child.type
2016-10-06 07:07:41 +00:00
// if child does not specify a href, specify it
// so that repetition is not needed by the user
2016-10-08 05:12:51 +00:00
if (!isAnchor || !('href' in child.props)) {
2016-10-06 07:07:41 +00:00
props.href = this.props.href
}
2016-10-08 05:12:51 +00:00
if (isAnchor) {
2016-10-06 07:07:41 +00:00
return React.cloneElement(child, props)
} else {
return <a {...props}>{child}</a>
}
})
return children[0]
}
}
function isLocal (href) {
const origin = location.origin
return !/^https?:\/\//.test(href) ||
origin === href.substr(0, origin.length)
}