-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(:wheelchair:) adding correct ARIA attribs
Switch was missing aeria-checked which is required. Adding a small hook util to help manage correct aria-checked attribute values when switch is used as an uncontrolled component
- Loading branch information
1 parent
f77511b
commit 01bc2f5
Showing
2 changed files
with
46 additions
and
1 deletion.
There are no files selected for viewing
This file contains 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
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import * as React from 'react'; | ||
import { PCRSwitchProps } from '../../typings/PCRSwitchProps'; | ||
|
||
export type UseAriaCheckedOptions = { | ||
setState?: PCRSwitchProps['setState']; | ||
checked?: PCRSwitchProps['checked']; | ||
}; | ||
|
||
const handler = (e: any) => { | ||
e.currentTarget.setAttribute('aria-checked', e.currentTarget.checked + ''); | ||
}; | ||
|
||
/** | ||
* A small hook to help manage correct aria-checked state when switch | ||
* is used as an uncontrolled component. | ||
*/ | ||
export const useAriaChecked = ({ setState, checked }: UseAriaCheckedOptions) => { | ||
const ref = React.useRef<HTMLInputElement>(null); | ||
|
||
React.useEffect(() => { | ||
const elem = ref.current; | ||
let bound = false; | ||
|
||
if (!setState && !checked && elem) { | ||
elem.setAttribute('aria-checked', elem.checked + ''); | ||
elem.addEventListener('change', handler); | ||
bound = true; | ||
} | ||
|
||
return () => { | ||
if (bound && elem) { | ||
elem.removeEventListener('change', handler); | ||
} | ||
}; | ||
}, [setState, checked]); | ||
|
||
return ref; | ||
}; |