Change Style on Pressable Click React Native

990 Views Asked by At

I am trying to create a custom button using pressable in react native but I cant change the style on press. Whenever I press on the pressable and change the style properties they reflect the change when I print it in the console but it isn't reflected in the app.

import { useState } from "react";
import { Pressable, StyleSheet, Text, View } from "react-native";


export default function Button(props) {
    const [refresh, setRefresh] = useState(10);

    function setBG() {
        styles.container.backgroundColor = 'red';
        setRefresh(1);
        console.log(styles.container.backgroundColor);
        console.log('called');
    }
    
    return (
        <Pressable onPress={setBG}>
            <View style = {styles.container}>
                <Text style = {styles.buttonLabel}>{props.text}</Text>
            </View>
        </Pressable>
    )
}

const styles = StyleSheet.create({
    container: {
        backgroundColor: 'blue',
        minWidth: 100,
        minHeight: 50,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center'
    },
    buttonLabel: {
        color: 'white',
        fontWeight: 700
    }
})
1

There are 1 best solutions below

0
On BEST ANSWER

You can pass a function for style that receives a boolean indicating whether it’s currently pressed and return the appropriate styles.

https://reactnative.dev/docs/pressable#style

You can also pass a render function as a child of pressable that receives a boolean indicating whether it’s currently pressed and returns the appropriate children.

https://reactnative.dev/docs/pressable#children

Using either or both of these you can render the appropriate state for pressed and unpressed.

No need to try to manage the state yourself. Pressable will hand it to you.