1 | import React, {Component, createContext, forwardRef} from 'react';
|
2 | import PropTypes from 'prop-types';
|
3 | import classNames from 'classnames';
|
4 |
|
5 | import getUID from '../global/get-uid';
|
6 |
|
7 | import styles from './radio.css';
|
8 |
|
9 | export const RadioContext = createContext({});
|
10 |
|
11 | export class Radio extends Component {
|
12 | static propTypes = {
|
13 | className: PropTypes.string,
|
14 | children: PropTypes.node,
|
15 | value: PropTypes.string,
|
16 | name: PropTypes.string,
|
17 | checked: PropTypes.bool,
|
18 | onChange: PropTypes.func
|
19 | };
|
20 |
|
21 | uid = getUID('ring-radio-item-');
|
22 |
|
23 | inputRef = el => {
|
24 | this.input = el;
|
25 | };
|
26 |
|
27 | labelRef = el => {
|
28 | this.label = el;
|
29 | };
|
30 |
|
31 | render() {
|
32 | const {className, children, ...restProps} = this.props;
|
33 |
|
34 | const classes = classNames(styles.radio, className);
|
35 |
|
36 | return (
|
37 | <label ref={this.labelRef} className={classes} htmlFor={this.uid}>
|
38 | <input
|
39 | name={name}
|
40 | id={this.uid}
|
41 | {...restProps}
|
42 | ref={this.inputRef}
|
43 | className={styles.input}
|
44 | type="radio"
|
45 | />
|
46 | <span className={styles.circle}/>
|
47 | <span className={styles.label}>{children}</span>
|
48 | </label>
|
49 | );
|
50 | }
|
51 | }
|
52 |
|
53 | export default forwardRef((props, ref) => (
|
54 | <RadioContext.Consumer>
|
55 | {({value, onChange, ...restContext}) => (
|
56 | <Radio
|
57 | ref={ref}
|
58 | {...restContext}
|
59 | checked={value != null ? value === props.value : undefined}
|
60 | onChange={onChange && (() => onChange(props.value))}
|
61 | {...props}
|
62 | />
|
63 | )}
|
64 | </RadioContext.Consumer>
|
65 | ));
|