Created
June 15, 2016 08:20
-
-
Save shprink/bf9599e1d66b9dc4d151e89c1199ccb8 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
import React from 'react'; | |
import {Link as ReactLink} from 'react-router'; | |
export default class Link extends React.Component { | |
parseTo(to) { | |
let parser = document.createElement('a'); | |
parser.href = to; | |
return parser; | |
} | |
isInternal(toLocation) { | |
return window.location.host === toLocation.host; | |
} | |
render() { | |
const {to, children, ...rest} = this.props; | |
const toLocation = this.parseTo(to); | |
const isInternal = this.isInternal(toLocation); | |
if (isInternal) { | |
return (<ReactLink to={toLocation.pathname} {...rest}>{children}</ReactLink>); | |
} else { | |
return (<a href={to} target="_blank" {...rest}>{children}</a>); | |
} | |
} | |
} |
V4 uses import {Link as ReactLink} from 'react-router-dom';
Here is an alternative utility function:
const isInternalURL = (to: string) => {
try {
const url = new URL(to, window.location.origin);
return url.hostname === window.location.hostname;
} catch {
return false;
}
};
Here is an alternative utility function:
const isInternalURL = (to: string) => { try { const url = new URL(to, window.location.origin); return url.hostname === window.location.hostname; } catch { return false; } };
This is awesome, thank you @colinschoen!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Perhaps you'd consider ditching the semicolon from
'://'
- protocol agnostic links won't work with your class (like//static.example.com/some/image.png
which work well and creatinga
element is not necessary - at least if there's a//
on the first char. :)