concept UI in category react native

appears as: UI, UI
React Native in Action

This is an excerpt from Manning's book React Native in Action.

At the top of the file, you require React from 'react', as well as View, Text, and StyleSheet from 'react-native'. View is the most fundamental building block for creating React Native components and the UI in general and can be thought of like a div in HTML. Text allows you to create text elements and is comparable to a span tag in HTML. StyleSheet lets you create style objects to use in an application. These two packages (react and react-native) are available as npm modules.

Figure 2.1 shows how the state is updated each time the text element in listing 2.3 is pressed. Every time setState is called, React will rerender the component (calling the render method again) and any child components. Calling this.setState is the way to change a state variable and trigger the render method again, because changing the state variable directly won’t trigger a rerender of the component and therefore no changes will be visible in the UI. A common mistake for beginners is updating the state variable directly. For example, something like the following doesn’t work when trying to update state—the state object is updated, but the UI isn’t updated because setState isn’t called and the component isn’t rerendered:

class MyComponent extends Component {
  constructor(){
    super()
    this.state = {
      year: 2016,
    }
  }
  updateYear() {
    this.state.year = 2017 
  }  
  render() {
    return (
      <View>
        <Text
          onPress={() => this.updateYear()}>
          The year is: { this.state.year }
        </Text>
      </View>
    )
  }
}

But a method is available in React that can force an update once a state variable has been changed as in the previous snippet. This method is called forceUpdate; see listing 2.4. Calling forceUpdate causes render to be called on the component, triggering a rerendering of the UI. Using forceUpdate isn’t usually necessary or recommended, but it’s good to know about in case you run into it in examples or documentation. Most of the time, this rerendering can be handled using other methods such as calling setState or passing in new props.

Figure 10.4 Rendering ProgressViewIOS in the UI

c10_04.tif