Last active
June 1, 2018 01:06
-
-
Save anthony2025/aa8a629a64bc3459b138c9e0fe1c1518 to your computer and use it in GitHub Desktop.
React-Router Link that handles falsy 'to' props and mailto links
This file contains hidden or 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
// @flow | |
// Handles empty links with proper defaults and allows mailto links | |
import React, { type Node } from 'react'; | |
import styled from 'styled-components'; | |
import { Link as RouterLink } from 'react-router-dom'; | |
type Props = { | |
link: ?string, | |
children: Node, | |
className?: Object, // gotta pass className to allow styling overrides | |
}; | |
export const isMailto = (link: ?string) => link && link.startsWith('mailto:'); | |
export const Link = styled(RouterLink).attrs({ | |
to: (props) => props.link || '#', | |
target: (props) => isMailto(props.link) ? '_blank' : '_self', | |
})` | |
&:hover, | |
&:focus { | |
color: ${(props) => props.link ? 'var(--accent)' : 'inherit'}; | |
} | |
cursor: ${(props) => props.link ? 'pointer' : 'auto'}; | |
`; | |
export default ({ | |
link, | |
children, | |
className, | |
}: Props) => ( | |
<Link | |
link={link} | |
className={className} | |
> | |
{children} | |
</Link> | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment