diff --git a/README.md b/README.md index bbdd2d6..ba0c068 100644 --- a/README.md +++ b/README.md @@ -63,6 +63,7 @@ npm install --save segmented-control - `disabled: true`: optional - `style: PropTypes.object`: common styles are width and color - `setValue: PropTypes.func`: callback on input change, passed the value string. Called once initially with the default value on mount. +- `selectedValue: PropTypes.string`: optional string value that enables programmatic selection of an option. Ensure the value passed exists as a value in the options. Note that selections will not change unless the selectedValue is updated. ```jsx import { SegmentedControl } from 'segmented-control' diff --git a/src/SegmentedControlWithoutStyles.js b/src/SegmentedControlWithoutStyles.js index c3bb756..ddc29be 100644 --- a/src/SegmentedControlWithoutStyles.js +++ b/src/SegmentedControlWithoutStyles.js @@ -9,18 +9,29 @@ class SegmentedControlWithoutStyles extends Component { name: PropTypes.string.isRequired, options: PropTypes.array.isRequired, style: PropTypes.object, - setValue: PropTypes.func + setValue: PropTypes.func, + selectedValue: PropTypes.string } componentWillMount() { - const defaultOption = find(this.props.options, { default: true }) - this.setValue(defaultOption.value) + let defaultOption = find(this.props.options, { default: true }) + if (this.selectedValueExists()) this.setValue(this.props.selectedValue) + else this.setValue(defaultOption.value) } setValue(val) { this.props.setValue && this.props.setValue(val) } + selectedValueExists = () => { + if (this.props.selectedValue) { + const exists = this.props.options.find( + (el) => el.value === this.props.selectedValue + ) + if (exists) return true + } else return false + }; + render() { const getId = option => this.props.name + option.value @@ -44,7 +55,11 @@ class SegmentedControlWithoutStyles extends Component { type="radio" name={this.props.name} id={getId(option)} - defaultChecked={option.default} + defaultChecked={ + this.selectedValueExists() + ? option.value === this.props.selectedValue + : option.default + } disabled={option.disabled} /> ))}