import * as React from 'react'; import { InputOption } from './InputOption'; export type OnSelection = (item) => void; export interface Props { options?: Array; defaultSelection?: string; reset?: boolean; inline?: boolean; onSelection?: OnSelection; } export interface State { defaultSelection: string; selected: string; } /** * A radio button group. * * Prop types: * options:Array: The list of options for the radio group. * defaultSelection:string:optional: Denotes the default value for the radio group. * reset:boolean: A flag that resets the selection to the default value. * onSelection:Function: The selection listener. The function must accept a string function (s:string) {}. * * @example * import {InputOption} from "./InputOption"; * let const options = (['Red', 'Green', 'Blue']).map(function (e) { * return new InputOption(e, e) * }); * * { static defaultProps: Props = { inline: false, reset: false, }; constructor(props) { super(props); let defaultSelection = ''; if ('defaultSelection' in this.props) { defaultSelection = this.props.defaultSelection; } else { if (this.props.options) { const options: Array = this.props.options; if (options.length > 0) { defaultSelection = options[0].value; } } } this.state = { defaultSelection: defaultSelection, selected: defaultSelection, }; if (!('options' in this.props)) { console.warn('RadioButtons: No options are available.'); } } componentDidUpdate() { if ('reset' in this.props && this.props.reset) { if (this.state.selected != this.state.defaultSelection) { this.setState({ selected: this.state.defaultSelection }); } } } onActionSelected = (e: React.SyntheticEvent) => { const target: HTMLInputElement = e.target as HTMLInputElement; this.setState({ selected: target.value }); if ('onSelection' in this.props) { this.props.onSelection(target.value); } }; render() { if ('options' in this.props) { const selected: string = this.state.selected; const isInline: boolean = this.props.inline; const options: Array = this.props.options; const radioButtonElements = options.map((d: InputOption) => { return (
); }); return
{radioButtonElements}
; } else { return null; } } }