React Native - Basics

Hey Guys!! Good Day!!
In previous post, we have done installation and setup for React Native. Today, Let's learn some basics of React Native.

Basically, React Native uses Android and IOS device's native components instead of using <div>, <span>, etc in WebView to design UI like other cross platforms. To use the Components, we have to know stuffs like Props and State first.

Props and State:

Props is nothing but that can be changed dynamically in a Component. Whereas, State can be referred as triggering method, which is used to update or refresh values in a Component. Each time when setState() method is calling , the render function of that Component will also be called simultaneously.

Let's learn about it with example.

Props:

React Native Components have default Props. Also we can create custom props for our own Components.

<Image 
source={
      {uri:'https://encrypted-tbn0.gstatic.com/images?   
               q=tbn:ANd9GcSVBDnlZthNR7G3d_PuyOD4IOSZIudG5Y_88_A4Gd5yHKAPM7lF'}

}
 style={{width: 200, height: 100}}/>

State:

Let's do an example for State with validation of Login Form. If the user didn't enter either FirstName or LastName then isValidated value will be false and an alert will be shown. Otherwise, the entered FirstName and LastName will be displayed below.

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

export default class App extends Component<{}> {

  constructor(props){
    super(props);

    this.state = {
      firstInput: "",
      secondInput: "",
      isValidated: false
    }
  }

  _displayResult(){
    console.log('Button has been pressed');
    if(this.state.firstInput !== "" && this.state.secondInput !== ""){
      this.setState({isValidated: true});
    }else{
      this.setState({isValidated: false});
      Alert.alert('Please enter both FirstName and LastName!!');
    }
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.viewWrapper}> 
          <Text style={styles.textColor}>Enter FirstName:</Text>
          <TextInput style={styles.inputbox} onChangeText={(inputValue) => this.setState({firstInput: inputValue})}  />
        </View>

        <View style={styles.viewWrapper}> 
          <Text style={styles.textColor}>Enter LastName:</Text>
          <TextInput style={styles.inputbox} onChangeText={(inputValue) => this.setState({secondInput: inputValue}) } />
        </View>

        <TouchableHighlight style={{alignSelf:'center'}} 
          onPress={() => {this. _displayResult()}}
          underlayColor='#b2c6d9'> 
          <Text style={styles.buttonStyle}>Login </Text>
        </TouchableHighlight>

         <View style={{margin:30}}>
           <Text style={styles.textColor}> {this.state.isValidated ? this.state.firstInput + " " +  this.state.secondInput : "" } </Text>
         </View>
        
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ffffff',
    padding:5
  },

  viewWrapper:{
    marginBottom: 30,
  },

  textColor:{
    color: '#000000'
  },

  inputbox: {
    width: 300,
    height: 35,
    color: '#000000'
  },
  buttonStyle: {
    color:'#ffffff',
    backgroundColor:'#004182', 
    padding:5,
    fontSize:12
  },
});

The following screens are the result of the above program.


     

Handling Touches:

You can handle touches normal Button or with following Touchable Components:
  • TouchableHighlight
  • TouchableOpacity
  • TouchableNativeFeedback
  • TouchableWithoutFeedback
(i) TouchableHighlight:

It let us see the underlayColor which we have given, when we touches the view which is wrapped inside it.

<TouchableHighlight style={{alignSelf:'center'}} 
          onPress={() => {this. _displayResult()}}
          activeOpacity=0.5> 
          <Text style={styles.buttonStyle}>Login </Text>
        </TouchableHighlight>

(ii) TouchableOpacity:

It makes the view dims while the user touches it. We can adjust the opacity which is to be happened.

<TouchableOpacity style={{alignSelf:'center'}} 
          onPress={() => {this. _displayResult()}}
          underlayColor='#b2c6d9'> 
          <Text style={styles.buttonStyle}>Login </Text>
        </TouchableHighlight>

(iii) TouchableNativeFeedback:

It works only in Android. It gives the ripple effect for the view, which we are enclosing in it. It uses background props to customize it.

(iv) TouchableWithoutFeedback:

It doesn't give any change while touching. Mostly we won't use it. 

ListView:

To display list of items, we can either use FlatList or SectionList.

FlatList is nothing but, similarly structured, displays a scrolling list of data. It have the following features:

  • Fully cross-platform
  • Optional Horizontal Mode
  • Configurable viewability callbacks
  • Header Support
  • Footer Support
  • Separator Support
  • PullToRefresh
  • Scroll loading
  • Scroll to Index Support

Example:

<FlatList
  data={[{key: 'Percy'}, {key: 'Leo'}]}
  renderItem={({item}) => <Text>{item.key}</Text>}
/>


SectionList is same, but it also contains header to certain no. of rows or data. For example, if you have to show all contacts in alphabetical order, you may want to show section header of an Alphabet to list of contacts, that have same first letter. In that case, you can use SectionList, like below:

      <SectionList
          sections={[
            {title: 'P', data: ['Percy', 'Piper']},
            {title: 'J', data: ['Jackson', 'Jason', 'Juniper', 'Jupiter']}
          ]}
          renderItem={({item}) => <Text>{item}</Text>}
          renderSectionHeader={({section}) => <Text>{section.title}</Text>}
          keyExtractor={(item, index) => index}
      />



Networking:

In React Native, we can make any network calls easily by using Fetch API, the one which is provided by React Native itself. 

fetch('https://jsonplaceholder.typicode.com/users')

This simple line can be used to pass URL to be fetched. We can also pass any parameters or headers as follows:

fetch('https://mywebsite.com/endpoint/', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
firstParam: 'yourValue',
secondParam: 'yourOtherValue',
}),
});
You can check the full doc for Fetch API , here.

Here, I have used Placehoder api for Users.

fetch('https://jsonplaceholder.typicode.com/users')
    .then((response) => response.json()) 
    .then((response) => {this.setState({
          dataSource: response,
        });
      })
    .catch((error) => {console.error(error);})

In this example, the following line is used to mention the type of the response, we are getting from the URL. We can also pass our Custom Model here.
.then((response) => response.json()) 

The following block is where the actions will be taken, as per our need.

                                                 .then((response) => {this.setState({
                                                        dataSource: response,
                                                      });
                                                  })
The catch block is to catch and display the error , if happens.

.catch((error) => {console.error(error);})

The following example contains both FlatList and Fetch API, to get and display list of data.

App.js

Here, we gonna use ActivityIndicator to let the user know that the page is loading. (Its nothing but, ProgressBar :p ) We should fetch the data from API, while the page launches. For that, default method, componentDidMount() is used. And from that api's response, we gonna set that data to FlatList and let it render on the screen.

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


export default class App extends Component {

  constructor(Props){
    super(Props)
    this.state = {isLoading : true}
  }

  componentDidMount(){
    return fetch('https://jsonplaceholder.typicode.com/users')
    .then((response) => response.json())
    .then((response) => {this.setState({
          isLoading: false,
          dataSource: response,
        });
      })
    .catch((error) => {console.error(error);})
  }

   renderSeparator = () => {
    return (
      <View
        style={{
          marginTop: 5,
          maringBottom : 5,
          height: 1,
          backgroundColor: "#000000",
        }}
      />
    );
  };

  render() {
    if(this.state.isLoading){
      return(
        <View style={{flex: 1, padding: 20, justifyContent: 'center}}>
          <ActivityIndicator/>
        </View>
      )
    }
    return (
      <View style={styles.container}>
      <FlatList
      data = {this.state.dataSource}
      ItemSeparatorComponent = {this.renderSeparator}
      renderItem = {({item}) =>
      <View>
      <Text> {item.name}</Text>
      <Text> Reach at {item.email}</Text>
      </View>
      }
    />
    </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F5FCFF',
  },
});

That's it. We have covered the basics of React Native now. Let's do explore more in future posts.

Comments

  1. Hey! This is my first visit to your blog! We are
    a collection of volunteers and starting
    a new project in a community in the same niche. Your blog provided us beneficial information to work on. You have done a marvellous job!

    React Native Development Company
    Reactjs Development Company Texas

    ReplyDelete
  2. Really this is very good information, if anyone wants to get basic information about React Native then this blog is very good. i will try to share this blog.React Js & React Native Developers in USA

    ReplyDelete
  3. Thank you for sharing this amazing informative blog. I learned a lot from this blog.
    Now I will use these basics in sending React Native push notificationss to users.
    Thanks again!

    ReplyDelete
  4. This blog post probably covers the basics of React Native development. It might include introductory information, tutorials, and explanations of key concepts related to React Native app development. A helpful resource for beginners looking to learn the foundational aspects of React Native and start building mobile apps using this framework. If you are looking forward to Hire Dedicated Flutter app Developers, we will gladly help you.

    ReplyDelete

Post a Comment

Popular posts from this blog

FlatList - PullToRefresh, Load More and Filtering implementation

AsyncStorage in React Native

FlatList - HorizontalList and GridList