-
Notifications
You must be signed in to change notification settings - Fork 182
/
radio__item.tsx
85 lines (72 loc) · 2.14 KB
/
radio__item.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import React, {
Component,
createContext,
forwardRef,
InputHTMLAttributes
} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import getUID from '../global/get-uid';
import styles from './radio.css';
export interface RadioProps extends Omit<InputHTMLAttributes<HTMLInputElement>, 'onChange'> {
value?: string | undefined
onChange?: ((value: string) => void) | null | undefined
}
export const RadioContext = createContext<RadioProps>({});
export class Radio extends Component<InputHTMLAttributes<HTMLInputElement>> {
static propTypes = {
className: PropTypes.string,
children: PropTypes.node,
value: PropTypes.string,
name: PropTypes.string,
checked: PropTypes.bool,
onChange: PropTypes.func
};
uid = getUID('ring-radio-item-');
input?: HTMLElement | null;
inputRef = (el: HTMLElement | null) => {
this.input = el;
};
label?: HTMLElement | null;
labelRef = (el: HTMLElement | null) => {
this.label = el;
};
render() {
const {className, children, ...restProps} = this.props;
const classes = classNames(styles.radio, className);
return (
<label ref={this.labelRef} className={classes} htmlFor={this.uid}>
<input
id={this.uid}
{...restProps}
ref={this.inputRef}
className={styles.input}
type="radio"
/>
<span className={styles.circle}/>
<span className={styles.label}>{children}</span>
</label>
);
}
}
export interface RadioItemProps extends InputHTMLAttributes<HTMLInputElement> {
value: string
}
const RadioItem = forwardRef<Radio, RadioItemProps>(function RadioItem(
props, ref) {
return (
<RadioContext.Consumer>
{({value, onChange, ...restContext}) => (
<Radio
ref={ref}
{...restContext}
checked={value != null ? value === props.value : undefined}
onChange={onChange != null ? () => onChange(props.value) : undefined}
{...props}
/>
)}
</RadioContext.Consumer>
);
});
RadioItem.propTypes = Radio.propTypes as (typeof RadioItem)['propTypes'];
export default RadioItem;