Skip to content

fix(Checkbox): mirror aria-checked to checked property of checkbox input #4263

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Feb 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/spicy-cobras-hunt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@primer/react': patch
---

Update Checkbox to mirror `aria-checked` and the input's `checked` property
36 changes: 29 additions & 7 deletions packages/react/src/Checkbox/Checkbox.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import styled from 'styled-components'
import {useProvidedRefOrCreate} from '../hooks'
import type {ChangeEventHandler, InputHTMLAttributes, ReactElement} from 'react'
import React, {useContext} from 'react'
import type {SxProp} from '../sx'
import sx from '../sx'
import React, {useContext, useEffect, type ChangeEventHandler, type InputHTMLAttributes, type ReactElement} from 'react'
import sx, {type SxProp} from '../sx'
import useLayoutEffect from '../utils/useIsomorphicLayoutEffect'
import type {FormValidationStatus} from '../utils/types/FormValidationStatus'
import {CheckboxGroupContext} from '../CheckboxGroup/CheckboxGroupContext'
Expand Down Expand Up @@ -142,7 +140,18 @@ const StyledCheckbox = styled.input`
*/
const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(
(
{checked, indeterminate, disabled, onChange, sx: sxProp, required, validationStatus, value, ...rest}: CheckboxProps,
{
checked,
defaultChecked,
indeterminate,
disabled,
onChange,
sx: sxProp,
required,
validationStatus,
value,
...rest
},
ref,
): ReactElement => {
const checkboxRef = useProvidedRefOrCreate(ref as React.RefObject<HTMLInputElement>)
Expand All @@ -158,13 +167,26 @@ const Checkbox = React.forwardRef<HTMLInputElement, CheckboxProps>(
}
}, [indeterminate, checked, checkboxRef])

useEffect(() => {
const {current: checkbox} = checkboxRef
if (!checkbox) {
return
}

if (indeterminate) {
checkbox.setAttribute('aria-checked', 'mixed')
} else {
checkbox.setAttribute('aria-checked', checkbox.checked ? 'true' : 'false')
}
})

return (
<StyledCheckbox
type="checkbox"
disabled={disabled}
ref={ref || checkboxRef}
ref={checkboxRef}
checked={indeterminate ? false : checked}
aria-checked={indeterminate ? 'mixed' : checked ? 'true' : 'false'}
defaultChecked={defaultChecked}
sx={sxProp}
required={required}
aria-required={required ? 'true' : 'false'}
Expand Down