Category: Javascript frameworks

  • Process to get data from Youtube XML : Part 7

    Process To Get Data From Youtube – If you will see youtube video.xml url, there are many xml node. We  need only all video id , thumbnail url to display image and Title to show on top of Card

    XML display data different way than Json. So first we parse xml data and use text to get its value.

    First install xmldom so run command

    npm install -S xmldom

    So after last import line, after a line line break  add parse function which will help to parse data of xml

    1. const DOMParser = require(‘xmldom’).DOMParser;

    before component start. For example

    …..

    const DOMParser = require(‘xmldom’).DOMParser;

    class VideoList extends Component {

    ………

    First you need to understand few things before we start coding. In this process I am going to use ComponentWillMount, fetch, and state

    componentWillMount: this is a lifecycle method . It invoke immediately before mounting occurs.

    Fetch: Fetch Networking api used in react native to get content from arbitrary URL

    For more details please take a look here

    https://facebook.github.io/react-native/docs/network.html


    Now in our next process we will use componentWillMount before render function and so

    So in VideoList.js remove condole.log(this.props.playlistid); and start writing componentWillMount()

    componentWillMount should be called before render() function of component

    But before componentWillMount function we will define a state video as array. Because after  fetch were are going to get data in array so open VideoList.js and add before render() function

    1. state = { videos: [], }
    2. componentWillMount() {
    3. const playerid = this.props.playlistid; /* to get playlist id value*/
    4. /* Now make url of youtube video smal feed */
    5. const url = ‘http://www.youtube.com/feeds/videos.xml?playlist_id=’ + playerid;
    6. /* now its time to fetch data from url */
    7. fetch(url)
    8. .then(Data => Data.text())
    9. /* now we will run console.log to check if data coming after fetch */
    10. .then(DataText => console.log(DataText));
    11. }

    Now refresh simulator and you will see xml data in condole.

    But this data is not in array and it is not useful for us to setState with array. As you can see we are getting whole xml as it is. To process our video listing we need a array of Title, Image and Video id. To process this we will process to parse data using a helper function . so create a function called getXMLData

    So in componentWillMount function add a new function

    1. componentWillMount() {
    2. const getXMLData = (listdata) => {
    3. }
    4. ……

    No we will expand our function getXMLData. In this function i have passed a parameter which is used to get data which we get from fetch and parse it

    So

    1. const getXMLData = (listdata) => {
    2. const parseData = new DOMParser().parseFromString(listdata, ‘text/xml’);
    3. const allVideoTitle = parseData.getElementsByTagName(‘title’);
    4. const allVideoId = parseData.getElementsByTagName(‘yt:videoId’);
    5. const allThumbnails = parseData.getElementsByTagName(‘media:thumbnail’);
    6. /* define a new array */
    7. const finalArray = [];
    8. /* push all items in one array */
    9. for (const i = 0; i < allVideoId.length; i++) {
    10. finalArray.push({
    11. title: allVideoTitle[i].textContent,
    12. id: allVideoId[i].textContent,
    13. thumbnail: allThumbnails[i].getAttribute(‘url’)
    14. });
    15. }
    16. return finalArray;
    17. };

    In above function you can see we have passed our listdata paramer in parseFromString and then we are getting title, video id and Thumbnail by tag name of xml. But is is not enough because we need a series of array in which we can get all values in one array

    So I created a variable with name finallArray as array then using for function I have adding each values in finalArray using push function

    Push: This  method help to add new item in  array

    Now our function returning array of all items which we need in one array. Now we will call this function to setState of Video array state. It may be little confusing but no need to worry much about it . I will show you further process

    Now go to this line of componentWillMount function

    .then(DataText => console.log(DataText));

    And now remove console.log(DataText) and replace with

    1. .then(DataText => this.setState({ videos: getXMLData(DataText) }));

    Here we have set state video with array using our helper function getXMLData passing Data of fetch

    Now if you need to check what is result of this video state you can write a line of console.log in render function of component.

    So go to render function of component and write like this

    render() {

       console.log(this.state);

       return (

    ………

    If you will open console you will see result as video array

    Now remove console.log from render function.

    1. import React, { Component } from ‘react’;
    2. import { View, Text } from ‘react-native’;
    3. import CardWrapper from ‘../common/CardWrapper’;
    4. import CardInner from ‘../common/CardInner’;
    5. const DOMParser = require(‘xmldom’).DOMParser;
    6. class VideoList extends Component {
    7. state = { videos: [], }
    8. componentWillMount() {
    9. const getXMLData = (listdata) => {
    10. const parseData = new DOMParser().parseFromString(listdata, ‘text/xml’);
    11. const allVideoTitle = parseData.getElementsByTagName(‘title’);
    12. const allVideoId = parseData.getElementsByTagName(‘yt:videoId’);
    13. const allThumbnails = parseData.getElementsByTagName(‘media:thumbnail’);
    14. /* define a new array */
    15. const finalArray = [];
    16. /* push all items in one array */
    17. for (const i = 0; i < allVideoId.length; i++) {
    18. finalArray.push({
    19. title: allVideoTitle[i].textContent,
    20. id: allVideoId[i].textContent,
    21. thumbnail: allThumbnails[i].getAttribute(‘url’)
    22. });
    23. }
    24. return finalArray;
    25. };
    26. const playerid = this.props.playlistid; /* to get playlist id value*/
    27. const url = ‘http://www.youtube.com/feeds/videos.xml?playlist_id=’ + playerid;
    28. fetch(url)
    29. .then(Data => Data.text())
    30. .then(DataText => this.setState({ videos: getXMLData(DataText) }));
    31. }
    32. render() {
    33. return (
    34. <View>
    35. <CardWrapper>
    36. <CardInner>
    37. <Text>For Title</Text>
    38. </CardInner>
    39. <CardInner>
    40. <Text>For Image</Text>
    41. </CardInner>
    42. <CardInner>
    43. <Text>For Buttons</Text>
    44. </CardInner>
    45. </CardWrapper>
    46. </View>
    47. );
    48. }
    49. }
    50. export default VideoList;
  • Process to call state values : Part 8

    Process to call state values : Part 8 – To run all array as loop using our CardWrapper and CardInner, We will use map function . map() will run our design and place value of each array items untill it is null

    So it will not be a good idea to write a code in return . I think we should make a helper function and use map and CardWrapper and CardInner component in this function and then call this function in return function.

    So create a funtion before render() function of VideoList component

    1. renderthumbnails() {
    2. return this.state.videos.map(video =>
    3. <CardWrapper key={video.id}>
    4. <CardInner>
    5. <View>
    6. <Text>{video.title}</Text>
    7. </View>
    8. </CardInner>
    9. <Image
    10. resizeMode={Image.resizeMode.cover}
    11. style={{ height: 280, width: null }}
    12. source={{ uri: video.thumbnail }}
    13. />
    14. <CardInner>
    15. <Text>{video.id}</Text>
    16. </CardInner>
    17. </CardWrapper>
    18. );
    19. }

    Now you can see in above code we are using Image component in card so go on top and we will import Image component from react-native so change import line like this

    1. import { View, Text, Image } from ‘react-native’;

    Now we are ready with our design and listing function so next step is to call this function in return. To call this function we will use curly braces using view component.

    So in return please remove all cardWrapper and CardInner code and  add code like this, we have already called these component in renderthumbnails function

    1. …..
    2. return (
    3. <View>
    4. {this.renderthumbnails()}
    5. </View>
    6. );
    7. ………

    Now refresh simulator and check result .. you can see all data with title image and video id

    But you can see page scroll is not working. So to fix this we will use <ScrollView> component

    Calling ScrollView component

    First import ScrollView from react-native so add ScrollView on top

    import { View, Text, Image, ScrollView } from ‘react-native’;

    And now add ScrollView in View so

    1. …….
    2. <View>
    3. <ScrollView>
    4. {this.renderthumbnails()}
    5. </ScrollView>
    6. </View>
    7. ……..

    Now scroll will work , check it by refreshing Simulator

    In Place of button i have called video ID . Now in further code we will create a button component in common folder and use it and then call video id on press to send to new screen .

  • Create a button component : Part 9

    To create a button component we will add new file in common folder of src. Button.js

    We will import React and Component from react and

    Text and TouchableOpacity from react-native

    Touchable opacity so some animation on press so we will use this and later we will call onPress funtion to navigate on another page to view video.

    So create Button.js file with this code

    1. import React, { Component } from ‘react’;
    2. import { Text, TouchableOpacity } from ‘react-native’;
    3. class Button extends Component {
    4. render() {
    5. return (
    6. <TouchableOpacity>
    7. <Text>View</Text>
    8. </TouchableOpacity>
    9. );
    10. }
    11. }
    12. export default Button;

    Now our button code is ready and we will call this button in VideoList helper fuction where we are calling video id in place of button

    So open VideoList.js

    Import button component import Button from ‘../common/Button’;

    Go to last CardInner component of helper function renderthumbnails() and replace Text with Button component

    Now refresh simulator and you will see view text there which we were added in Button component

    Now we are going to process button design so open Button.js and add some styling

    Styling of Button component

    1. const styles = {
    2. buttonstyles: {
    3. flex: 1,
    4. alignSelf: ‘stretch’,
    5. borderRadius: 4,
    6. borderColor: ‘#000’,
    7. borderWidth: 1,
    8. backgroundColor: ‘#ff0000’
    9. },
    10. buttonTextstyle: {
    11. fontSize: 16,
    12. color: ‘#FFF’,
    13. paddingTop: 10,
    14. paddingBottom: 10,
    15. alignSelf: ‘center’,
    16. fontWeight: ‘600’
    17. }
    18. };

    Now call these styles in TouchableOpacity and Text of Button component

    1. return (
    2. <TouchableOpacity style={styles.buttonstyles}>
    3. <Text style={styles.buttonTextstyle}>View</Text>
    4. </TouchableOpacity>
    5. );

    Now refresh simulator and you will see button style is changed to red

    Now we need to pass Button pass a props when Button component is pressed . When we press button then a props should be pass to TouchableOpacity on press. Button component press will not work on press until we add press function on TouchableOpacity so

    So add

    1. <TouchableOpacity onPress={this.props.onPress} style={styles.buttonstyles}>
    2. <Text style={styles.buttonTextstyle}>View</Text>
    3. </TouchableOpacity>

    Now we can make button text more editable so anyone can easily change where they call <Button /> component so we will add children same as we did for Cards components

    1. <TouchableOpacity onPress={this.props.onPress} style={styles.buttonstyles}>
    2. <Text style={styles.buttonTextstyle}>{this.props.children}</Text>
    3. </TouchableOpacity>

    So now button can be called with desired button text like this

    <Button> Button Text Here </Button>

    So Open VideoList.js and change button like this

    <Button>

    View

    </Button>

    Now please reload Simulator and check design

    So page is ready to display with all video listing. In further process i am going to use navigation to play video on new page with id.

  • Navigation Screen Using React Navigation : Part 10

    Navigation in react native is based on many plateform which you can install and use from npm. I am going to use here react navigator

    So open terminal or command prompt and run this command

    npm install –save react-navigation

    If you want to read more about react navigation please go here https://facebook.github.io/react-native/docs/navigation.html

    When installation is complete. Please open root file index.js and we will create Screen and use it . Here i am going to use react-navigation to import StackNavigator so you can easily understand how navigator work in react native

    To define screen we will use index.js and in that file we will define YoutubeVideo component to load first. We have added YoutubeVideo in App.js and already imported on index.js on root

    So first import stack navigator  in index.js on top. So after this line

    import { AppRegistry } from ‘react-native’;

    add

    1. import { StackNavigator, } from ‘react-navigation’;

    Now create new screen component in index.js

    1. const AppNav = StackNavigator({
    2. YoutubeVideo: {
    3. screen: YoutubeVideo
    4. }
    5. });

    And in app registry change component name AppNav

    1. AppRegistry.registerComponent(‘youtube_video’, () => AppNav);

    Now refresh simulator and see same screen will show

    It means you are in right direction and react navigator is working

    So your index.js file whole code should look like this

    1. import { StackNavigator, } from ‘react-navigation’;
    2. import { AppRegistry } from ‘react-native’;
    3. import YoutubeVideo from ‘./App’;
    4. const AppNav = StackNavigator({
    5. YoutubeVideo: {
    6. screen: YoutubeVideo
    7. }
    8. });
    9. AppRegistry.registerComponent(‘youtube_video’, () => AppNav);

    Note: “if you are getting 500 error after installation of React Navigation, Please delete it and re-install by npm command. To delete please use command npm uninstall –save react-navigation”

  • Calling Screens in Stack Navigator : Part 11

    Calling Screens In Stack Navigator- Here one need to notice. When we use navigation we should call all component through navigator props. If you will include direct then props from one component to another component will not go and we get error when navigate.

    So before video play we will change all component call using navigate function . Here is further process

    So first import all component pages in index.js

    1. import ViewVideo from ‘./src/components/ViewVideo’;
    2. import VideoList from ‘./src/components/VideoList’;
    3. import Index from ‘./src/components/Index’;

    Then define screen for all components

    1. YoutubeVideo: {
    2. screen: YoutubeVideo
    3. },
    4. Index: {
    5. screen: Index
    6. },
    7. VideoList: {
    8. screen: VideoList
    9. }

    Now our index.js page code should look like this

    1. import React from ‘react’;
    2. import { StackNavigator, } from ‘react-navigation’;
    3. import { AppRegistry } from ‘react-native’;
    4. import YoutubeVideo from ‘./App’;
    5. import VideoList from ‘./src/components/VideoList’;
    6. import Index from ‘./src/components/Index’;
    7. const AppNav = StackNavigator({
    8. YoutubeVideo: {
    9. screen: YoutubeVideo
    10. },
    11. Index: {
    12. screen: Index
    13. },
    14. VideoList: {
    15. screen: VideoList
    16. }
    17. });
    18. AppRegistry.registerComponent(‘youtube_video’, () => AppNav);

    so now our all screen are added in Stack Navigator function. Now we call any screen to load by using navigation props anywhere without import. Now in next post i will show you how we can call any page instead of import

  • Calling component by navigation props : Part 12

    Calling component by navigation props- So first open App.js . In this file we have called Index component so now we will call this using navigation here

    So make a function renderIndex before render() function and call it in return

    1. renderIndex() {
    2. this.props.navigation.navigate(‘Index’);
    3. }

    And in return () function after header component replace <Index /> with

    1. { this.renderIndex() }

    So now our Index component from Index.js component will load by navigator

    So remove import Index from ‘./src/components/Index’; from this App.js

    Now we will do same for VideoList component which is called in Index.js

    So again i will create a function in components/Index.js file

    1. renderVideoList() {
    2. this.props.navigation.navigate(‘VideoList’, {
    3. playlistid: ‘LLA34Z3lq8FozSQzDHsSLcmQ’
    4. });
    5. }

    And now i should replace VideoList with this function

    1. { this.renderVideoList() }

    And remove import from this file 

    import VideoList from ‘./VideoList’;

    Here you can see I am passing a props of playlistid which i will get on VideoList page like this now

    Find this line

    const playerid = this.props.playlistid

    & change with

    1. const playerid = this.props.navigation.state.params.playlistid

    To get navigation props value we use this.props.navigation.state.params.propsname

    Now in further step we will make a new page to play video and link that page to this navigation . After linking this page to navigation we will call that page on button click and pass a props as video id . After that on View video page we will display video by youtube video id

  • Creating component to display video : Part 13

    Creating Component To Display Video – So I added further now we wil make a new file in components folder ViewVideo.js

    Now we will start adding code in that so first import React and Component

    1. import React, { Component } from ‘react’;
    2. import { View, Text } from ‘react-native’;
    3. class ViewVideo extends Component {
    4. render() {
    5. return (
    6. <View>
    7. <Text>We will play video here…</Text>
    8. </View>
    9. );
    10. }
    11. }
    12. <span style=”font-weight: 400;”>export default ViewVideo;</span>

    Now we will create screen on navigation and call this page. So open index.js on root

    So first import  ViewVideo on index

    1. import ViewVideo from ‘./src/components/ViewVideo’;

    Not add screen for this so add after comma

    1. …….
    2. YoutubeVideo: {
    3. screen: YoutubeVideo
    4. },
    5. Index: {
    6. screen: Index
    7. },
    8. VideoList: {
    9. screen: VideoList
    10. },
    11. ViewVideo: {
    12. screen: ViewVideo
    13. }
    14. ……

    Now our screen is ready to call as navigator. we have button on each video as View. So we will call on Press function to pass props and video id and send to ViewVideo page.

    Open VideoList.js file and find code where <Button /> added

    Add onPress function in it

    1. <Button onPress={() => this.props.navigation.navigate(‘ViewVideo’, { vidid: video.id })}>

    this.props.navigation.navigate this function call screen and send to that screen which is added in ‘ ‘ second parameter is props . i have taken vidid as props and assigned video id value to it

    So now we will refresh simulator 

  • Passing Navigation props to screen : Part 14

    Passing Navigation props to screen – Open View Video.js file and get props video id . so our code should be to get value.

    this.props.navigation.state.params.vidid;

    so add

    1. const videoId = this.props.navigation.state.params.vidid;

    Now we can call { vidid } and use to display videoid which is clicked on VideoList page. So to check it 

    Now in return we will call vidid in Text

    So change Text like this

    1. <Text>{vidid}</Text>

    Now refresh simulator and click on button of any video you will see that video id on that page

    Now import WebView from react-native

    WebView use to embed any url on page . It is same like we use iframe in normal html code. So we will use youtube embed url to embed video here using this component

    Now in return add this code

    1. <WebView
    2. source={{ uri: ‘https://www.youtube.com/embed/’ + videoId }}
    3. />
  • Modifying Navigation & Header : Part 15

    Modifying Navigation & Header – Copy api key and add in ViewVideo youtube parameter which was null. Now your code is ready to play video.

    But you can see a arrow in header of page. If you would like to remove it you nee to pass a option in navigator.

    So add this new code

    const options = {

     header: null

    };

    And now we will call this navigation option in StackNavigator so your code should look like this

    const AppNav = StackNavigator({

       YoutubeVideo: {

         screen: YoutubeVideo

       },

       Index: {

         screen: Index

       },

       VideoList: {

         screen: VideoList

       },

       ViewVideo: {

         screen: ViewVideo

       }

     },

       {

         navigationOptions: options

       }

    );

    Final code of screen in index.js

    1. import { AppRegistry } from ‘react-native’;
    2. import { StackNavigator } from ‘react-navigation’;
    3. import YoutubeVideo from ‘./App’;
    4. import VideoList from ‘./src/components/VideoList’;
    5. import Index from ‘./src/components/Index’;
    6. import ViewVideo from ‘./src/components/ViewVideo’;
    7. const options = {
    8. header: null
    9. };
    10. const AppNav = StackNavigator({
    11. YoutubeVideo: {
    12. screen: YoutubeVideo
    13. },
    14. Index: {
    15. screen: Index
    16. },
    17. VideoList: {
    18. screen: VideoList
    19. },
    20. ViewVideo: {
    21. screen: ViewVideo
    22. }
    23. },
    24. {
    25. navigationOptions: options
    26. }
    27. );
    28. AppRegistry.registerComponent(‘youtube_video’, () => AppNav);

    Now you can see we have blank page when go back , it is because we have Index screen to load then video list screen to load, So now we will do some modifications to use navigator header and remove Index component

    Final touch

    Now open VideoList.js and change variable with this code

    1. const url = ‘http://www.youtube.com/feeds/videos.xml?playlist_id=LLA34Z3lq8FozSQzDHsSLcmQ’;

    Now you can see i have directly added playlist id in const url

    Well, Now we will create a function to render navbar header

    1. renderNavBar() {
    2. return (
    3. <View style={styles.navBar}>
    4. <TouchableOpacity style={styles.logo} >
    5. <Text style={styles.text}>Pankaj Bhadouria Masterchef</Text>
    6. </TouchableOpacity>
    7. </View>
    8. );
    9. }

    and call this function in render function of component where header is called, So remove Header component and add

    1. render() {
    2. return (
    3. <View>
    4. { this.renderNavBar() }
    5. <ScrollView>
    6. {this.renderthumbnails()}
    7. </ScrollView>
    8. </View>
    9. );
    10. }

    If you want to show video title of youtube on view video page so pass video.title props in onPress function so change like this

    1. <Button
    2. onPress={() => this.props.navigation.navigate(‘ViewVideo’, { vidid: video.id, vidtitle: video.title })}
    3. >

    and finally open ViewVideo.js and call this props like this

    1. import React, { Component } from ‘react’;
    2. import { View, WebView } from ‘react-native’;
    3. import NavBar from ‘../common/NavBar’;
    4. class ViewVideo extends Component {
    5. render() {
    6. const videoId = this.props.navigation.state.params.vidid;
    7. const videoTitle = this.props.navigation.state.params.vidtitle;
    8. return (
    9. <View style={{ flex: 1 }}>
    10. <NavBar
    11. navigator={this.props.navigation}
    12. title={videoTitle}
    13. />
    14. <WebView
    15. source={{ uri: `https://www.youtube.com/embed/${videoId}` }}
    16. />
    17. </View>
    18. );
    19. }
    20. }
    21. export default ViewVideo;

    Now our application is ready to play youtube video . If you need to find code you can find it on GIT

    In this tutorial we learned how to install react native , create component, create design , navigation and parse video xml of youtube

    Hope you enjoyed it !!