React Native – State

The data is managed by state and props inside React Components.

Two types of data components

  • props
  • state

While props are immutable and state are mutable. This means that props will never change anytime and state can be changed later. We use setState to update the state when we want.

In this example we will see Text component with “Click me :)” text. Once user clicks on text the state will be changed using onPress method and new message will be displayed “The state has changed” .

import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  Text,
} from 'react-native';

export default class App extends Component {  
  state = {  
      newStates: 'Click me :)'  
  }  
  
  changeState = () => this.setState({newStates: 'The state has changed'})  
  render() {  
      return (  
          <View style={styles.container}>  
           <Text style={styles.setFontSize } onPress={this.changeState}> {this.state.newStates} </Text>  
          </View>  
      );  
  }  
}  

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center'
  },
  setFontSize: {
    fontSize: 25 // Define font size here in Pixels
  }});