Skip to content

Commit

Permalink
add a utility to convert tab names with spaces to dashes, fix a11y ch…
Browse files Browse the repository at this point in the history
…eck for aria-controls (#7766)

* add a utility to convert tab names with spaces to dashes, fix a11y check for aria-controls

* add unique ID to name conversion

* Update src/components/BlockSwitcher/BlockSwitcher.tsx

* Update src/components/BlockSwitcher/BlockSwitcher.tsx
  • Loading branch information
josefaidt committed Jun 20, 2024
1 parent cb300ef commit d5403a7
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions src/components/BlockSwitcher/BlockSwitcher.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Children } from 'react';
import { Children, useId } from 'react';
import { View, Tabs } from '@aws-amplify/ui-react';
import { BlockProps } from './Block';

Expand All @@ -10,17 +10,30 @@ export const BlockSwitcherErrorMessage =
'BlockSwitcher requires more than one block element';

export const BlockSwitcher = ({ children }: BlockSwitcherProps) => {
const uniqueId = useId();

if (!children.length || children.length <= 1) {
throw new Error(BlockSwitcherErrorMessage);
}

/**
* convert names with spaces to valid ID attribute values
*/
const convertNameToValue = (name: string) => {
return `${name.split(' ').join('-').toLowerCase()}-${uniqueId}`;
};

return (
<View className="block-switcher">
<Tabs.Container defaultValue={children[0].props.name}>
<Tabs.Container defaultValue={convertNameToValue(children[0].props.name)}>
<Tabs.List>
{Children.map(children, (child, index) => {
return (
child.props.name && (
<Tabs.Item value={child.props.name} key={index}>
<Tabs.Item
value={convertNameToValue(child.props.name)}
key={index}
>
{child.props.name}
</Tabs.Item>
)
Expand All @@ -30,7 +43,10 @@ export const BlockSwitcher = ({ children }: BlockSwitcherProps) => {
{Children.map(children, (child, index) => {
return (
child.props.name && (
<Tabs.Panel value={child.props.name} key={index}>
<Tabs.Panel
value={convertNameToValue(child.props.name)}
key={index}
>
{child}
</Tabs.Panel>
)
Expand Down

0 comments on commit d5403a7

Please sign in to comment.