Search code examples
react-nativebuttonpressable

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>
    );
}

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>
        );
    }