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>
);
}
}
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)
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With