Last active
March 15, 2019 15:48
-
-
Save joshpensky/6241f695362d6e96df0a17def1654af9 to your computer and use it in GitHub Desktop.
React/Vue universal Link component
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 PropTypes from 'prop-types'; | |
// This example uses the Link component from 'react-router-dom' | |
// but can use any internal routing link component provided | |
// by a package (like Link from 'gatsby') | |
import { Link as RouterLink } from 'react-router-dom'; | |
const Link = ({ children, newTab, to }) => { | |
const isInternal = /^\/(?!\/)/.test(to); | |
const isFile = /\.[0-9a-z]+$/i.test(to); | |
const useInternalLink = isInternal && !isFile; | |
const Component = useInternalLink ? RouterLink : 'a'; | |
const props = { | |
[useInternalLink ? 'to' : 'href']: to, | |
}; | |
if (newTab && !useInternalLink) { | |
props.target = '_blank'; | |
props.rel = 'noopener noreferrer'; | |
} | |
return <Component {...props}>{children}</Component>; | |
}; | |
Link.defaultProps = { | |
newTab: false, | |
}; | |
Link.propTypes = { | |
children: PropTypes.node, | |
newTab: PropTypes.bool, | |
to: PropTypes.string.isRequired, | |
}; | |
export default Link; |
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
<template> | |
<component :is="linkComponent" v-bind="linkProps"> | |
<slot /> | |
</component> | |
</template> | |
<script> | |
export default { | |
name: 'Link', | |
props: { | |
to: { | |
type: String, | |
required: true, | |
}, | |
newTab: { | |
type: Boolean, | |
default: false, | |
}, | |
}, | |
computed: { | |
isInternal() { | |
const internal = /^\/(?!\/)/.test(this.to) || /^#/.test(this.to); | |
const file = /\.[0-9a-z]+$/i.test(this.to); | |
return internal && !file; | |
}, | |
linkComponent() { | |
return this.isInternal ? 'router-link' : 'a'; | |
}, | |
linkProps() { | |
const props = { | |
[this.isInternal ? 'to' : 'href']: this.to, | |
}; | |
if (this.newTab && !this.isInternal) { | |
props.target = '_blank'; | |
props.rel = 'noopener noreferrer'; | |
} | |
return props; | |
}, | |
}, | |
}; | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment