I am converting React code to React Native. So I need to implement radio buttons.
You can use react-native-radio-input. Its very simple to use.
import RadioGroup,{Radio} from "react-native-radio-input";
.
.
.
//Receive the checked value (ES6 syntax)
getChecked = (value) => {
// value = our checked value
alert(value)
}
<RadioGroup getChecked={this.getChecked}>
<Radio iconName={"lens"} label={"The first option"} value={"A"} />
<Radio iconName={"lens"} label={"The first option"} value={"B"} />
<Radio iconName={"lens"} label={"I need numbers"} value={1} />
<Radio label={"Is IconName Optional?"} value={"Yes"} />
<Radio label={"Show Sentence Value"} value={"This is a Sentence"} />
</RadioGroup>
.
.
Here is my solution for radio button using functional components.
Note - I have used images for checked & unchecked radio icon
import React, {useState} from 'react';
import {View, Text, StyleSheet, TouchableOpacity, Image} from 'react-native';
const Radio = () => {
const [checked, setChecked] = useState(0);
var gender = ['Male', 'Female'];
return (
<View>
<View style={styles.btn}>
{gender.map((gender, key) => {
return (
<View key={gender}>
{checked == key ? (
<TouchableOpacity style={styles.btn}>
<Image
style={styles.img}
source={require('../images/radio_Checked.jpg')}
/>
<Text>{gender}</Text>
</TouchableOpacity>
) : (
<TouchableOpacity
onPress={() => {
setChecked(key);
}}
style={styles.btn}>
<Image
style={styles.img}
source={require('../images/radio_Unchecked.png')}
/>
<Text>{gender}</Text>
</TouchableOpacity>
)}
</View>
);
})}
</View>
{/* <Text>{gender[checked]}</Text> */}
</View>
);
};
const styles = StyleSheet.create({
radio: {
flexDirection: 'row',
},
img: {
height: 20,
width: 20,
marginHorizontal: 5,
},
btn: {
flexDirection: 'row',
alignItems: 'center',
},
});
export default Radio;