Skip to content

Instantly share code, notes, and snippets.

@jtrefry
Created October 13, 2016 00:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jtrefry/bd827065e22b6d6f8a94add71fb970ee to your computer and use it in GitHub Desktop.
Save jtrefry/bd827065e22b6d6f8a94add71fb970ee to your computer and use it in GitHub Desktop.
RadioButtonGroup for Grommet RadioButtons
import React, { Component, PropTypes as t } from 'react';
import RadioButton from 'grommet/components/RadioButton';
import FormField from 'grommet/components/FormField';
class RadioButtonGroup extends Component {
constructor(props) {
super(props);
this._onChange = this._onChange.bind(this);
}
_onChange(event, option) {
const { onChange, value, defaultValue } = this.props;
if (onChange) {
const checked = event.target.checked;
const newValue = checked ? option : (value || defaultValue);
onChange(newValue);
}
}
render() {
const { id, name, options, defaultValue, value, disabled, onBlur } = this.props;
//get the current or default value as a string
let val = value || defaultValue;
if (typeof val === 'object') {
const opt = options.find(o => o.value === val);
if (opt)
val = opt.value;
}
const radioButtons = options.map(option => {
//If the value assigned to the group is equal to this item, this item is checked
const checked = (option.value === val);
return <RadioButton
key={option.value}
id={`${id}-${option.value}`}
name={name}
label={option.label}
value={option.value}
checked={checked}
disabled={disabled}
onChange={event => this._onChange(event, option)}
onBlur={event => onBlur && onBlur(event, option)}/>
});
if (this.props.formFieldProps) {
return <FormField {...this.props.formFieldProps}>
{radioButtons}
</FormField>
} else {
//Avoid if possible.
//Grommet CSS expects the RadioButtons to be direct children
// of FormField for proper styling
return <div id={id}>
{radioButtons}
</div>
}
}
}
RadioButtonGroup.propTypes = {
id: t.string,
name: t.string,
onChange: t.func,
onBlur: t.func,
disabled: t.bool,
options: t.arrayOf(t.oneOfType([t.shape({
label: t.node,
value: t.any
}), t.string])).isRequired,
defaultValue: t.oneOfType([t.shape({
label: t.string,
value: t.string
}), t.string]),
value: t.oneOfType([t.shape({
label: t.string,
value: t.string
}), t.string]),
formFieldProps: t.object
};
export default RadioButtonGroup;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment