Reputation: 3522
I have been working on a custom component that acts similar to a radio button, but now have a few questions on how I can extend it.
I want to be able set TouchableOpacity style via a stylesheet which is currently done inline due to the dynamic nature of it.
I also want to be able to pass a second variable/string in price through.
Further to the above if I can send through 2 variables these will be coming via firebase/props so how would I expose them.
Component
import React, { Component } from 'react'
import { View, Text, TouchableOpacity } from 'react-native'
import styles from './Styles/OptionStyle'
export default class Option extends Component {
constructor(props) {
super(props);
this.state = {
activeOption: this.props.options[0],
};
}
updateActiveOption = (activeOption) => {
this.setState({
activeOption,
});
};
render() {
return (
<View style={styles.container}>
{this.props.options.map((option, index) => (
<TouchableOpacity key={index} style={styles.button}
onPress={() => {
this.props.onChange(option);
this.updateActiveOption(option);
}}
>
<Text
style={{
width: 100,
borderWidth: 1,
borderColor: this.state.activeOption === option ? '#4caf50' : 'rgb(117, 117, 118)',
borderRadius: 6,
height: 100,
padding: 10,
color: this.state.activeOption === option ? '#4caf50' : 'rgb(117, 117, 118)'
}}
>
{option}
</Text>
</TouchableOpacity>
))}
</View>
);
}
}
Calling the component
<Option
options={['Small','Medium','Large']}
onChange={(option) => {
console.log(option);
}}
/>
This is where I would like to be able to pass 2 variables per option ie Small and $3.95 or Medium and $4.95
Upvotes: 0
Views: 2220
Reputation: 127
You can pass array of objects via props and then use them in your component. Something like this:
<Option
options={[{label: 'Small', price: '$3.95'},{label: 'Medium', price: '$4.95'}]}
onChange={(option) => {
console.log(option);
}}
/>
And then in your Component simply iterate over it for example with map:
{this.props.options.map((option, index) => (
<TouchableOpacity><Text>{option.label} - {option.value}</Text></TouchableOpacity>
))}
Upvotes: 1