Last active
March 25, 2020 16:27
-
-
Save mahowa/87fbd6d4deb3e08141114db6c3123005 to your computer and use it in GitHub Desktop.
React Accessible link. Outline only when keyboard focus (emotion.js/styled-components.js)
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 | |
| import React from 'react'; | |
| import styled from '@emotion/styled'; //or styled-components | |
| export const Content = styled.span` | |
| cursor: pointer; | |
| display: flex; | |
| align-content: center; | |
| position: relative; | |
| flex: 1; | |
| &:focus { | |
| outline: none; | |
| } | |
| `; | |
| export const Anchor = styled.a` | |
| all: initial; | |
| font: inherit; | |
| display: inline-flex; | |
| visibility: inherit; | |
| & span { | |
| color: ${({ color }) => color || null}; | |
| text-decoration: ${({ underline }) => (underline ? 'underline' : 'none')}; | |
| &:hover { | |
| color: ${({ highlightColor }) => highlightColor || null}; | |
| } | |
| } | |
| &:focus > ${Content} { | |
| box-shadow: 0 0 2px 2px ${colors.nfRedHover}; | |
| } | |
| &:focus { | |
| outline: none; | |
| } | |
| `; | |
| type Props = $Exact<{ | |
| href?: string, | |
| onClick?: () => void, | |
| ariaLabel: string, | |
| children: React.Node, | |
| role?: ?string, | |
| target?: ?string, | |
| color?: ?string, | |
| highlightColor?: ?string, | |
| rel?: ?string, | |
| onKeyUp?: (e: any) => void | Promise<void>, | |
| type?: string, | |
| as?: string, | |
| tabIndex?: number, | |
| underline?: boolean, | |
| }>; | |
| const AccessibleLink = ({ | |
| href, | |
| onClick, | |
| ariaLabel, | |
| children, | |
| role, | |
| ...rest | |
| }: Props) => | |
| href ? ( | |
| <Anchor | |
| role={role || 'link'} | |
| href={href} | |
| onClick={onClick} | |
| aria-label={ariaLabel} | |
| {...rest} | |
| > | |
| <Content tabIndex={-1}>{children}</Content> | |
| </Anchor> | |
| ) : ( | |
| <Anchor | |
| role={role || 'button'} | |
| onClick={onClick} | |
| aria-label={ariaLabel} | |
| as={rest.as || 'button'} | |
| {...rest} | |
| > | |
| <Content tabIndex={-1}>{children}</Content> | |
| </Anchor> | |
| ); | |
| AccessibleLink.defaultProps = { | |
| // eslint-disable-next-line no-script-url | |
| href: '', | |
| onClick: () => {}, | |
| role: null, | |
| target: null, | |
| color: null, | |
| rel: null, | |
| }; | |
| export default AccessibleLink; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment