From 10f182b2d15c1f8390abcf2771c21ceff1b2e89c Mon Sep 17 00:00:00 2001 From: Justin Tijunelis <35385306+Tijunel@users.noreply.github.com> Date: Thu, 4 Mar 2021 21:47:54 -0700 Subject: [PATCH] Implemented programmatic option selection --- README.md | 1 + src/SegmentedControlWithoutStyles.js | 23 +++++++++++++++++++---- 2 files changed, 20 insertions(+), 4 deletions(-) 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} /> ))}