Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implemented programmatic option selection #40

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
23 changes: 19 additions & 4 deletions src/SegmentedControlWithoutStyles.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd replace this line with return exists

} else return false
};

render() {
const getId = option => this.props.name + option.value

Expand All @@ -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}
/>
))}
Expand Down