Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Native – onPress not changing radio button style

When i click my Pressable RadioButton i want it to change the button style from styles.radio to styles.checked. so that it fills the empty circle. How can i implement this so that it happens when user is pressing my RadioButton? Right not nothing happens on the click, just gettin the console message.

type RadioProps = {
    checked: boolean;
    onPress: () => void;
    disabled?: boolean;
    checked: boolean;
};

export function RadioButton({ checked, disabled, onPress }: RadioProps) {
return (
    <Pressable
        style={styles.container}
        onPress={onPress}
        disabled={disabled}
    >
        <View style={[styles.radio, checked && styles.checked]}></View>
        <Text style={styles.text}>
            Label
        </Text>
    </Pressable>
);
}
const styles = StyleSheet.create({
radio: {
    width: 24,
    height: 24,
    borderRadius: 12,
    borderWidth: 1,
    borderColor: "gray",
},

checked: {
    borderColor: "red",
    backgroundColor: "white",
    borderWidth: 3,
    justifyContent: "center",
    alignItems: "center",
},

container: {
    flexDirection: "row",
},

text: {
    marginLeft: 16,
    color: theme.color.gray3,
},
});

App.tsx file

export default function App() {
    return (
        <View>
            <RadioButton
                onPress={() => {
                    console.log("pressed");
                }}
                checked={checked}
            />
        </View>
    );
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You are not changing the checked state which is defined in App. You need to change the state or nothing will happen.

export default function App() {
    const [checked, setChecked] = useState(false);
    return (
        <View>
            <RadioButton
                onPress={() => {
                    console.log("pressed");
                    setChecked(prev => !prev);
                }}
                checked={checked}
            />
        </View>
    );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading