To Manage the component data in React Native props and state

Here we are going to learn about state

State

In general, we would initialize state in the constructor, and will call setState when we want to change it.

Example

import React from 'react';

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

 

export default class App extends React.Component {

  state = {

    text:

      'React Native : State Chapter. Here we are going to learn what is React Native State and how to change state of a component.',

  };

  render() {

    return (

      <View

        style={{

          flex: 1,

          justifyContent: 'center',

          alignItems: 'center',

          padding: 20,

        }}>

        <Text

          style={{

            fontSize: 20,

          }}>

          {this.state.text}

        </Text>

 

        <Text

          style={{

            fontSize: 20,

            margin: 20,

            padding: 20,

          }}

          onPress={() => this.setState({text: 'Chapter Completed '})}>

          Mark Complete

        </Text>

      </View>

    );

  }

}

 

While running get output as

On Tap on Mark Complete we are changing the state by setState().

We will also learn how to use the arrow function syntax for setState. We should keep in mind that this syntax uses the lexical scope, and this keyword will be bound to the environment object (Class). This will sometimes lead to unexpected behavior

 


Subscribe For Daily Updates