Forked from shprink/Link component that handle internal or external links
Last active
August 4, 2018 05:08
-
-
Save binaryhq/8283eef18087c2df1d3161e544725aaf to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default class Link extends React.Component { | |
parseTo(to) { | |
let parser = document.createElement('a'); | |
parser.href = to; | |
return parser; | |
} | |
isInternal(to) { | |
// If it's a relative url such as '/path', 'path' and does not contain a protocol we can assume it is internal. | |
if(to.indexOf("://")=== -1) return true; | |
const toLocation = this.parseTo(to); | |
return window.location.hostname === toLocation.hostname; | |
} | |
render() { | |
const {to, children, ...rest} = this.props; | |
const isInternal = this.isInternal(to); | |
if (isInternal) { | |
return (<ReactLink to={to} {...rest}>{children}</ReactLink>); | |
} else { | |
return (<a href={to} target="_blank" {...rest}>{children}</a>); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment