Skip to content

Commit

Permalink
fix: replace card button with link (#2750)
Browse files Browse the repository at this point in the history
Co-authored-by: Brandon Lenz <15805554+brandonlenz@users.noreply.github.com>
  • Loading branch information
klalicki and brandonlenz committed Mar 4, 2024
1 parent afb9a52 commit 59d5f14
Show file tree
Hide file tree
Showing 3 changed files with 142 additions and 35 deletions.
9 changes: 7 additions & 2 deletions src/components/Link/Link.stories.tsx
Expand Up @@ -59,10 +59,15 @@ export const NavLink = (): React.ReactElement => (

export const StyledAsButton = (): React.ReactElement => (
<p>
<Link className="usa-button" variant="unstyled" href={'#'}>
<Link
className="usa-button"
variant="unstyled"
allowSpacebarActivation
href={'#'}>
This
</Link>
is a link styled to look like a button.
is a link styled to look like a button; it can be activated with the
spacebar.
</p>
)

Expand Down
21 changes: 19 additions & 2 deletions src/components/Link/Link.tsx
Expand Up @@ -6,6 +6,7 @@ type StyledLinkProps<T> = {
variant?: 'external' | 'unstyled' | 'nav'
className?: string
children: React.ReactNode
allowSpacebarActivation?: boolean
} & T

// These props are only required on the default Link
Expand Down Expand Up @@ -33,6 +34,13 @@ export function isCustomProps<T>(
): props is CustomLinkProps<T> {
return 'asCustom' in props
}
// keyboard handler for 'link as a button'
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === ' ' && e.target) {
e.preventDefault()
;(e.target as HTMLElement).click()
}
}

function linkClasses<T>(
variant: StyledLinkProps<T>['variant'],
Expand Down Expand Up @@ -75,11 +83,20 @@ export function Link<
children
)
} else {
const { children, className, variant, ...linkProps } = props
const {
children,
className,
variant,
allowSpacebarActivation = false,
...linkProps
} = props

const classes = linkClasses(variant, className)
return (
<a className={classes} {...linkProps}>
<a
className={classes}
{...(allowSpacebarActivation && { onKeyDown: handleKeyDown })}
{...linkProps}>
{children}
</a>
)
Expand Down

0 comments on commit 59d5f14

Please sign in to comment.