Home > Software engineering >  custom radio buttons not working in react native
custom radio buttons not working in react native

Time:12-15

i am creating custom radio btns. my code is as follows:

 const [isAvailable, setIsAvailable] = useState([
{id: 0, value: true, title: 'Always available', selected: true},
{id: 1, value: false, title: 'Never available', selected: false},
{
  id: 2,
  value: false,
  title: 'Availabe for specific hours',
  selected: false,
},
 ]);

Now, my radio component is being called by a series of assets, but the basic idea is that when i call the radio component, the respective view is shown. The radio btns are called as follows:

{isAvailable.map(option => (
      <Row
        key={option.id}
        rightComponent={'radio'}
        title={option.title}
        onPress={() => onPress(option)}
        isSwitched={option.selected}
      />
    ))}

And my OnPress function looks like this:

const onPress = option => {
setIsAvailable(
  isAvailable.map(isAvailableOption => {
    isAvailableOption.id === option.id
      ? {...isAvailableOption, selected: true}
      : {...isAvailableOption, selected: false};
  }),
);

};

Now, my Row component looks like this:

rightComponent === 'radio' ? (
          <TouchableOpacity
            style={styles.radioBtn}
            onPress={onPress}
            key={key}>
            {isSwitched === true ? (
              <>
                <Ionicons
                  name={'radio-button-on-outline'}
                  style={{...styles.rightIcon, ...rightIconColor}}
                />
              </>
            ) : (
              <>
                <Ionicons
                  name={'ellipse-outline'}
                  style={{...styles.rightIcon, ...rightIconColor}}
                />
              </>
            )}
          </TouchableOpacity>
        ) : ({...})

But, whenever I click any icon, it doesn't work, please tell me where am I going wrong here?

CodePudding user response:

Firstly you should use custom radio button because of this problems and you should use

//flexDirection:'row' in <View> <TouchableOpacity style={{//Your style}}/></View>`insted of Row. Like:` 
<View style={{flexDirection:'row"}}>
 <View>
{isAvailable.map(option => (
     <TouchableOpacity onPress={() => onPress(option)} style={{option.isSwitched ? style:style}} >
       <Text>optin.title </Text>
    </TouchableOpacity>
    ))}
</View>

CodePudding user response:

Nothing was wrong, I just had to put my TouchableOpacity inside a View

  • Related