Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React Native - State Changing but Component is not re-rendering

I am making a menu for changing the type of the Google Maps API but the state pressed is not working as I intended. Note that state inside the Text component is not being re-rendered after this.state.pressed is changed on the function setPressedState and it is not re-rendering on the component that contains MapMenu component after using getPressed.

Note: the Alert shows that state pressed is being changed.

class MapMenu extends Component{
    constructor(props){
        super(props);

        this.state = {
            pressed: 'standard'
        }
    }

    setPressedState(press){
        this.state.pressed = press;
        Alert.alert(this.state.pressed)
    }

    getPressed(){
        return(this.state.pressed);
    }

    render(){
        return(
            <View style={styles.container}>
            <View style={{backgroundColor: 'red'}}><Text>{this.state.pressed}</Text></View>

                <TouchableOpacity   style={styles.button}
                                    onPress={() => this.setPressedState('standart')}
                >
                    <Text>Mapa</Text>
                </TouchableOpacity>
                <TouchableOpacity   style={styles.button}
                                    onPress={() => this.setPressedState('hybrid')}
                >
                    <Text>Hibrido</Text>
                </TouchableOpacity>
                <TouchableOpacity   style={styles.button}
                                    onPress={() => this.setPressedState('satellite')}
                >
                    <Text>Satellite</Text>
                </TouchableOpacity>
            </View>
        );
    }
}
like image 551
Francisco Pena Avatar asked Mar 05 '26 13:03

Francisco Pena


1 Answers

To re-render component, you'll need to use setState method, as mentioned in the official documentation, that says:

In general, you should initialize state in the constructor, and then call setState when you want to change it.

See this,

setPressedState = (press) => {
    this.setState({pressed:press}, () => {
      Alert.alert(this.state.pressed)
    });
}
like image 76
Jaydeep Galani Avatar answered Mar 08 '26 10:03

Jaydeep Galani