Files
deighton-ar/mobile/src/ui/OptionStrip.js
2018-04-03 17:25:59 -07:00

71 lines
2.4 KiB
JavaScript

import React, { Component } from 'react'
import { View, Text, TouchableHighlight } from 'react-native'
import PropTypes from 'prop-types'
import autobind from 'autobind-decorator';
export class OptionStrip extends Component {
static propTypes = {
options: PropTypes.arrayOf(PropTypes.shape({ value: PropTypes.string, text: PropTypes.string })).isRequired,
value: PropTypes.string.isRequired,
onValueChanged: PropTypes.func,
}
constructor(props) {
super(props)
this.state = {
selectedOption: this.getSelectedOption(props.options, props.value)
}
}
@autobind
getSelectedOption(options, value) {
return options.find((option) => (value === option.value)) || options[0]
}
componentWillReceiveProps(newProps) {
if (newProps.options !== props.options || newProps.value !== props.value) {
this.setState({ selectedIndex: this.getSelectedIndex(newProps.options, newProps.value)})
}
}
@autobind
handlePress(option) {
const { onValueChanged } = this.props
this.setState({ selectedOption: option })
if (onValueChanged) {
onValueChanged(option.value)
}
}
render() {
const { style, options, value } = this.props
const { selectedOption } = this.state
return (
<View style={{ flexDirection: 'row' }}>
{options.map((option, index) => (
<TouchableHighlight
key={index}
underlayColor='#3BB0FD'
style={[
{ flexGrow: 1, flexBasis: 0, height: 40 },
option === selectedOption && { backgroundColor: '#3BB0FD' },
index === 0 && { borderTopLeftRadius: 6, borderBottomLeftRadius: 6 },
index === options.length - 1 && { borderTopRightRadius: 6, borderBottomRightRadius: 6 }
]}
onPress={() => this.handlePress(option)}>
<View style={[
{ flex: 1, justifyContent: 'center', borderTopWidth: 1, borderBottomWidth: 1, borderLeftWidth: 1, borderColor: 'black' },
index === 0 && { borderTopLeftRadius: 6, borderBottomLeftRadius: 6 },
index === options.length - 1 && { borderRightWidth: 1, borderTopRightRadius: 6, borderBottomRightRadius: 6 }
]}>
<Text style={{ alignSelf: 'center', color: 'black' }}>{option.text}</Text>
</View>
</TouchableHighlight>
))}
</View>
)
}
}