cuz
Version:
Front-end modular development kit.
62 lines (54 loc) • 1.45 kB
JavaScript
import React, { cloneElement } from 'react';
import classNames from 'classnames';
import {utils} from 'react-bootstrap';
function getDefaultActiveKeyFromChildren(children) {
let defaultActiveKey;
utils.ValidComponentChildren.forEach(children, (child, index) => {
if (child.props.checked === true) {
defaultActiveKey = index;
}
});
return (defaultActiveKey + 1);
}
const RadioGroup = React.createClass({
propTypes: {
defaultActiveKey: React.PropTypes.any,
children: React.PropTypes.any,
onSelect: React.PropTypes.func,
vertical: React.PropTypes.bool,
},
getInitialState() {
const defaultKey = this.props.defaultActiveKey || getDefaultActiveKeyFromChildren(this.props.children);
return {
checkedKey: defaultKey,
vertical: false,
};
},
onSelect(value, index) {
const { onSelect } = this.props;
this.setState({
checkedKey: index
});
if (onSelect) {
onSelect(value, index);
}
},
renderRadioItem(child, index) {
return cloneElement(
child,
{
checked: (index + 1) === this.state.checkedKey,
eventKey: (index + 1),
onSelect: this.onSelect
}
);
},
render() {
return (
<div className={classNames({'form-inline': !this.props.vertical})}>
{utils.ValidComponentChildren.map(this.props.children, this.renderRadioItem)}
</div>
);
}
});
export default RadioGroup;