-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathCheckbox.tsx
65 lines (58 loc) · 1.74 KB
/
Checkbox.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
'use client';
import { FC, Fragment, InputHTMLAttributes, ReactNode, createElement as h, useRef, useState } from 'react';
import { ClassBuilder } from '@not-govuk/component-helpers';
import { Hint } from '@not-govuk/hint';
import { Label } from '@not-govuk/label';
export type CheckboxProps = Omit<InputHTMLAttributes<HTMLInputElement>, 'label'> & {
classes: ClassBuilder
conditional?: ReactNode
hint?: string
label: string
};
export const Checkbox: FC<CheckboxProps> = ({
classes,
conditional,
hint,
id,
label,
onChange: _onChange,
...attrs
}) => {
const setState = useState({})[1];
const forceUpdate = () => setState({});
const withUpdate = <A, B>(f?: (a: A) => B) => (e: A): B | undefined => {
forceUpdate();
return f && f(e);
};
const onChange = withUpdate(_onChange);
const ref = useRef<HTMLInputElement>(null);
const conditionalId = `conditional-${id}`;
const isChecked = () => ref.current?.checked;
return (
<Fragment>
<div className={classes('item')}>
<input
{...attrs}
id={id}
className={classes('input')}
type="checkbox"
ref={ref}
onChange={onChange}
aria-controls={conditional ? conditionalId : undefined}
aria-expanded={conditional ? !!isChecked() : undefined}
/>
<Label htmlFor={id} className={classes('label')}>{label}</Label>
{hint && <Hint id={`${id}-hint`} className={classes('hint')}>{hint}</Hint>}
</div>
{ !conditional ? null : (
<div
id={conditionalId}
className={classes('conditional', isChecked() ? undefined : 'hidden')}
>
{conditional}
</div>
) }
</Fragment>
);
};
export default Checkbox;