Monday, May 20, 2019

React Native navigate Specific View of ScrollView on Button Click Android iOS

This tutorial explains how can we navigate specific view of full width ScrollView  component on button click by providing view number. We will try to make this example as simple as possible. In our last tutorial we have discussed React Native Full Width Horizontal ScrollView example right, so this example will be using to navigate specific view on button click.
For your information react native ScrollView component doesn’t support any predefined method to navigate specific view of full width ScrollView component by just providing view number. So, you have to make it custom. Yes, this tutorial explains how we can make it custom from scratch with complete source code.

React Native navigate Specific View of ScrollView on Button Click Android iOS

       Demo                  Download

React Native navigate Specific View On Button click

Lets follow the below steps that helps to navigate specific view of full width ScrollView  component on button click by providing view number.

Project Structure :
React Native navigate Specific View of ScrollView on Button Click Android iOS


Step 1: Create a new react native project, if you don’t know how to create a new project in react native just follow this tutorial.

Step 2: Lets create a new component named as CustomScrollView. This component helps user to navigate between different user screen, when user provides valid page number in textinput component and click on "Go To View" button.
  • The most important statement is this.props.children . This statement is a special type of prop which is passed to components automatically. Basically, this.props.children  can hold any simple text value, a Single element or Multiple elements. Using React.Children.count(this.props.children)  we can get length of child elements. You will know the reason behind to use this property when we will create our second custom component.
  • scrollTo  method is used to scroll the CustomScrollView component programatically in both horizontal and vertical directions. In our case, we have Horizontal ScrollView so we have to scroll the CustomScrollView component in horizontal direction.
  • this.state.getTextInput  is a state variable which is used to hold the TextInput  value. We have to multiply the device width with this.state.getTextInput - 1  value and then assign the resultant value to the X parameter of the scrollTo  method to scroll the ScrollView on desired View.
Lets see the complete source code for CustomScrollView.js file.

CustomScrollView
import React, { Component } from 'react';
import { AppRegistry, Text, View, ScrollView, Dimensions, TouchableOpacity, TextInput, StyleSheet, Platform } from 'react-native';

var deviceWidth = Dimensions.get('window').width;

export default class CustomScrollView extends Component
{
  constructor()
  {
    super();
    this.state = { getTextInput: '' }
  }

  moveToPage()
  {
    if( this.state.getTextInput === '' )
    {
      alert('Please enter some text');
    }
    else if(( this.state.getTextInput > React.Children.count( this.props.children )) || ( this.state.getTextInput <= 0 ))
    {
      alert('View not found...');
    }
    else
    {
      this.refs.scrollView.scrollTo({ x: (( this.state.getTextInput - 1 ) * deviceWidth ), y: 0, animated: true });
    }  
  }
  
  render()
  {
    return(
      <View style = { styles.container }>
        <ScrollView ref = "scrollView" showsHorizontalScrollIndicator = { false } horizontal = { true } pagingEnabled = { true }>
          { this.props.children }
        </ScrollView>
        
        {
          (React.Children.count( this.props.children ) <= 1)
          ?
            null
          :
            (<View style = { styles.secondLayoutContainer }>
              <View style = { styles.textInutHolder }>
                <TextInput onChangeText = {(text) => this.setState({ getTextInput: text })} style = { styles.textInputLayout } underlineColorAndroid = "transparent"/>
                <TouchableOpacity activeOpacity = { 0.8 } onPress = { this.moveToPage.bind(this) } style = { styles.buttonLayout }>
                  <Text style = { styles.textColor }>GoTo View</Text>
                </TouchableOpacity>
              </View> 
            </View>)
        }
      </View>
    );
  }
}



const styles = StyleSheet.create(
{
  container: {
    flex: 1,
    position: 'relative',
    marginTop: (Platform.OS === 'ios') ? 20 : 0
  }, 
   secondLayoutContainer:{    
    width: '100%',    
  },
  textInutHolder: {
    position: 'relative',
    margin: 15
  },
  textInputLayout: {
    borderWidth: 1,
    borderColor: 'rgba(0,0,0,0.5)',
    width: '100%',
    height: 40,
    paddingHorizontal: 15,
    backgroundColor: 'white',
    
  },
  buttonLayout :  {
    backgroundColor: '#2196f3',
    height: 39,
    position: 'absolute',
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 10,
    right: 0,
    top: 0,    
  },
});

Step 3: Open App.js File in your favorite code editor and erase all code and follow this tutorial.

Step 4: Through react , react-native  packages import all required components.
import React, { Component } from 'react';
import { AppRegistry, Text, View, ScrollView, Dimensions, TouchableOpacity, TextInput, StyleSheet, Platform } from 'react-native';
import CustomScrollView from "./src/components/CustomScrollView.js";

Step 5: Create a global variable above the class named as deviceWidth. This variable is used store the current device width, So the current view expand all over the screen. We would retrieve the device width using Dimensions.get(‘window’).width inbuilt method.
var deviceWidth = Dimensions.get('window').width;

Step 6: Implement render method inside the App class and wrapped the below layout design inside the root View component.
export default class App extends Component {
  constructor() {
    super();
  }

  render() {
    return (
      <CustomScrollView>
        <View style={styles.firstView}>
          <Text style={styles.headerText}>First View</Text>
        </View>

        <View style={styles.secondView}>
          <Text style={styles.headerText}>Second View</Text>
        </View>

        <View style={styles.thirdView}>
          <Text style={styles.headerText}>Third View</Text>
        </View>

        <View style={styles.forthView}>
          <Text style={styles.headerText}>Forth View</Text>
        </View>
      </CustomScrollView>
    );
  }
}

Step 7 : Apply the below style sheet design.
const styles = StyleSheet.create(
  {
    container: {
      flex: 1,
      justifyContent: "center",
      alignItems: "center",

    },
    headerText: {
      fontSize: 30,
      textAlign: "center",
      margin: 10,
      color: 'white',
      fontWeight: "bold"
    },

    firstView: {
      width: deviceWidth,
      backgroundColor: '#F44336',
      justifyContent: 'center',
      alignItems: 'center',
      flexDirection: 'row'
    },
    secondView: {
      width: deviceWidth,
      backgroundColor: '#9C27B0',
      justifyContent: 'center',
      alignItems: 'center',
      flexDirection: 'row'
    },
    thirdView: {
      width: deviceWidth,
      backgroundColor: '#3F51B5',
      justifyContent: 'center',
      alignItems: 'center',
      flexDirection: 'row'
    },
    forthView: {
      width: deviceWidth,
      backgroundColor: '#009688',
      justifyContent: 'center',
      alignItems: 'center',
      flexDirection: 'row'
    },
  });

Lets see the complete source code for App.js component.

App.js
import React, { Component } from 'react';
import { AppRegistry, Text, View, ScrollView, Dimensions, TouchableOpacity, TextInput, StyleSheet, Platform } from 'react-native';
import CustomScrollView from "./src/components/CustomScrollView.js";

var deviceWidth = Dimensions.get('window').width;

export default class App extends Component {
  constructor() {
    super();
  }

  render() {
    return (
      <CustomScrollView>
        <View style={styles.firstView}>
          <Text style={styles.headerText}>First View</Text>
        </View>

        <View style={styles.secondView}>
          <Text style={styles.headerText}>Second View</Text>
        </View>

        <View style={styles.thirdView}>
          <Text style={styles.headerText}>Third View</Text>
        </View>

        <View style={styles.forthView}>
          <Text style={styles.headerText}>Forth View</Text>
        </View>
      </CustomScrollView>
    );
  }
}

const styles = StyleSheet.create(
  {
    container: {
      flex: 1,
      justifyContent: "center",
      alignItems: "center",

    },
    headerText: {
      fontSize: 30,
      textAlign: "center",
      margin: 10,
      color: 'white',
      fontWeight: "bold"
    },

    firstView: {
      width: deviceWidth,
      backgroundColor: '#F44336',
      justifyContent: 'center',
      alignItems: 'center',
      flexDirection: 'row'
    },
    secondView: {
      width: deviceWidth,
      backgroundColor: '#9C27B0',
      justifyContent: 'center',
      alignItems: 'center',
      flexDirection: 'row'
    },
    thirdView: {
      width: deviceWidth,
      backgroundColor: '#3F51B5',
      justifyContent: 'center',
      alignItems: 'center',
      flexDirection: 'row'
    },
    forthView: {
      width: deviceWidth,
      backgroundColor: '#009688',
      justifyContent: 'center',
      alignItems: 'center',
      flexDirection: 'row'
    },
  });

Screenshot :
React Native navigate Specific View of ScrollView on Button Click Android iOS

React Native navigate Specific View of ScrollView on Button Click Android iOS

React Native navigate Specific View of ScrollView on Button Click Android iOS

This is all about React Native navigate Specific View of ScrollView on Button Click Android iOS. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.

1 comment: