Website Links

Monday 3 April 2017

React Native #8 - State

Previously, we discussed how we can make reusable components by passing data to a component using props. State can also be used to help us provide data to a component. However, the difference is that state is used to hold values that change, and when it changes it will trigger updates to the components that reference it. State should generally be initialised in the constructor, and set state should be used to update it.

As a simple example, consider a UI that has a text input for the users name and then a text component that greets them, it would appear as follows:

  // Import necessary components
  import React, { Component } from 'react';
  import { Text, View, TextInput, StyleSheet } from 'react-native';
  import { Constants } from 'expo';
  
  export default class App extends Component {
 
    // Initialise state to avoid state being undefined
    // state is just a javascript object with properties
    // want to keep track of the state of
    constructor(props) {
      super(props);
      this.state = { text: '' };
    }
    
    render() {
      return (
        <View style={styles.container}>
          // Render text input and when text changes
          // update state
          <TextInput
            placeholder='Name'
            style={styles.textInput}
            onChangeText={(text) => this.setState({text})}
            value={this.state.text}
          />
        
          // Render text when text changes for input
          // the hello message should update to match
          // the new state
          <Text style={styles.paragraph}>
            Hello {this.state.text}
          </Text>
        </View>
      );
    }
  }

  const styles = StyleSheet.create({
    container: {
      flex: 1,
      alignItems: 'center',
      justifyContent: 'center',
      paddingTop: Constants.statusBarHeight,
      backgroundColor: '#ecf0f1',
    },
    paragraph: {
      margin: 24,
      fontSize: 18,
      fontWeight: 'bold',
      textAlign: 'center',
      color: '#34495e',
    },
    textInput: {
      height: 40,
      borderColor: 'gray', 
      borderWidth: 1
    }
  });

No comments:

Post a Comment