Skip to content

Commit

Permalink
Merge pull request #2554 from adevinta/visually-hidden-aschild
Browse files Browse the repository at this point in the history
feat(visually-hidden): added asChild prop to VisuallyHidden
  • Loading branch information
Powerplex authored Jan 16, 2025
2 parents 9f85b49 + 1c2b96d commit 0931c1c
Show file tree
Hide file tree
Showing 4 changed files with 28 additions and 2 deletions.
3 changes: 3 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions packages/components/visually-hidden/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@
"scripts": {
"build": "vite build"
},
"dependencies": {
"@spark-ui/slot": "^8.0.2"
},
"peerDependencies": {
"react": "^19.0",
"react-dom": "^19.0",
Expand Down
13 changes: 13 additions & 0 deletions packages/components/visually-hidden/src/VisuallyHidden.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,17 @@ describe('VisuallyHidden', () => {
// Then
expect(screen.getByRole('button', { name: 'Checkmark', hidden: true })).toBeInTheDocument()
})

it('should render as alternative html tag using asChild prop', () => {
render(
<VisuallyHidden asChild>
<h3>Hidden heading</h3>
</VisuallyHidden>
)

// Then
expect(
screen.getByRole('heading', { name: 'Hidden heading', hidden: true })
).toBeInTheDocument()
})
})
11 changes: 9 additions & 2 deletions packages/components/visually-hidden/src/VisuallyHidden.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
import { Slot } from '@spark-ui/slot'
import { HTMLAttributes, PropsWithChildren, Ref } from 'react'

export type VisuallyHiddenProps = PropsWithChildren<HTMLAttributes<HTMLElement>> & {
/**
* Change the default rendered element for the one passed as a child, merging their props and behavior.
*/
asChild?: boolean
ref?: Ref<HTMLElement>
}

export const VisuallyHidden = ({ ref, ...props }: VisuallyHiddenProps) => {
export const VisuallyHidden = ({ asChild = false, ref, ...props }: VisuallyHiddenProps) => {
const Component = asChild ? Slot : 'span'

return (
<span
<Component
{...props}
ref={ref}
style={{
Expand Down

0 comments on commit 0931c1c

Please sign in to comment.