Behaviour of the application: props and state

Using props is a way of customizing and reusing React Native components. Props can be used by referring to this.props inside the components render function, and then supplying a prop with that name when using the component. (Facebook 2016.)
Props should be considered immutable and should never be modified directly inside the component, instead they are used by adding an attribute to the component when calling it. (Holmes & Bray, 2015.)

The following example in Figure is using a props called name to display a greeting for each different name. Props are used as a part of a simple component inside the render –method (line 7) and then just supplied to the Greeting component as parameters

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

class Hello extends Component {
  render() {
    return(
<Text> Hello {this.props.name}!</text>
);
  }
}
class MyGreetings extends Component {
 render(){
  return(
 <View style={{alignItems:'center'}}>
 <Greeting name = 'Jose'/>
 <Greeting name = 'William' />
 <Greeting name = 'Alice' />
 </View>
 )
 }
}

Props is what makes React Native so powerful, allowing users to invent any kind of reusable UI components they can imagine (Facebook 2016).
While props can be used to display static immutable data, state is a data type in React Native used for data that is going to change over time. State is generally used by initializing the state in the components constructor, and then setting the state to anything at any time, using a function called setState. (Facebook 2016.) State is a good way to store any user input and can be used to keep track of any asynchronous requests or events (Holmes & Bray 2015).

An example of this is a Blink component in Figure 5, initializing the state in the constructor (line 7) and toggling it every 1000 milliseconds (lines 10-12). Based on the state of the component, it’s either shown normally in a element (line 18), or not shown at all (line 16). The example is using the ternary operator, so if (in line 16) the this.state.showText is true, the operation evaluates to this.props.text, but if it’s false, the operation evaluates to an empty string.
import React, { Component } from 'react';
import { AppRegistry, Text, View } from 'react-native';

class Hello extends Component {
  constructor(props){
     super(props);
this.state = {showText:true};

setInterval(()=>{

this.setState({showText: !this.state.showText})
},1000);
  }
 
  render() {
   let display = this.state.showText ? this.props.text : '';
 
   return (
   <Text>{display}</Text>
 
   );
  }
 
}



Comments

Popular posts from this blog

Size & Dimensions & onLayout

Data - Networking - Fetch

Absolute & Relative