React Native – AppDividend https://appdividend.com Latest Code Tutorials Mon, 18 Mar 2019 08:59:14 +0000 en-US hourly 1 https://wordpress.org/?v=5.1.1 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png React Native – AppDividend https://appdividend.com 32 32 React Native Swipe Components Example Tutorial https://appdividend.com/2018/08/13/react-native-swipe-components-example-tutorial/ https://appdividend.com/2018/08/13/react-native-swipe-components-example-tutorial/#respond Mon, 13 Aug 2018 08:58:12 +0000 http://localhost/wordpress/?p=1473 React Native Swiper Component Example

React Native Swipe Components Example Tutorial is today’s leading topic.  We use react-native-swiper – A dominant React Native swipe component. It is the best Swiper component for React Native. Let us first install React Native on mac and start working on our demo example. If you want to learn more about React Native and Redux then check out this course. […]

The post React Native Swipe Components Example Tutorial appeared first on AppDividend.

]]>
React Native Swiper Component Example

React Native Swipe Components Example Tutorial is today’s leading topic.  We use react-native-swiper – A dominant React Native swipe component. It is the best Swiper component for React Native. Let us first install React Native on mac and start working on our demo example.

If you want to learn more about React Native and Redux then check out this course. The Complete React Native and Redux Course

React Native Swipe Components Example Tutorial

We will test this demo example in both Android and iOS simulators.

#1: Install React Native.

Type the following command in your terminal to install React Native CLI globally, if you have not installed previously.

npm install -g react-native-cli

Create a new React Native project using the following command.

react-native init swiper

Go into the project folder.

cd swiper

Install the react-native-swiper library using the following command.

npm i react-native-swiper --save

# or

yarn add react-native-swiper

#2: Modify App.js file and add swiper component.

Replace the App.js code with the following code.

// App.js

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

import Swiper from 'react-native-swiper';

export default class App extends Component {
  render(){
    return (
      <Swiper style={styles.wrapper} showsButtons={true}>
        <View style={styles.slide1}>
          <Text style={styles.text}>Hello Swiper</Text>
        </View>
        <View style={styles.slide2}>
          <Text style={styles.text}>Beautiful</Text>
        </View>
        <View style={styles.slide3}>
          <Text style={styles.text}>And simple</Text>
        </View>
      </Swiper>
    );
  }
}

const styles = StyleSheet.create({
  wrapper: {
  },
  slide1: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'red',
  },
  slide2: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#97CAE5',
  },
  slide3: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#92BB',
  },
  text: {
    color: '#fff',
    fontSize: 30,
    fontWeight: 'bold',
  }
})

Explanation

Here, we have included the Swiper component as a wrapper component. We have passed the one property called showButtons, and its value is true.  So that makes control buttons visible.

Also, we have given the styles to all the parent and child components, and that makes different each component.

Properties

Some of the props are the following.

Prop Default Type Description
horizontal true bool If true, the scroll view’s children are arranged horizontally in a row instead of vertically in a column.
loop true bool Set to false to disable continuous loop mode.
index 0 number Index number of initial slide.
showsButtons false bool Set to true make control buttons visible.
autoplay false bool Set to true enable auto play mode.
onIndexChanged (index) => null func Called with the new index when the user swiped

 

We have used the showButtons prop. Autoplay = { true} means components are sliding automatically.

// App.js 

<Swiper style={styles.wrapper} 
     showsButtons = { true }
     autoplay = { true }>
        <View style={styles.slide1}>
          <Text style={styles.text}>Hello Swiper</Text>
        </View>
        <View style={styles.slide2}>
          <Text style={styles.text}>Beautiful</Text>
        </View>
        <View style={styles.slide3}>
          <Text style={styles.text}>And simple</Text>
        </View>
</Swiper>

Same you can check and apply different properties based on your requirements.

Now to check the output, type the following command. We are first testing on an iOS simulator.

 

React Native Swipe Components Example Tutorial

Here you can see the three slides are there and played automatically because we have set autoplay to true.

Now, let us open on Android Emulator.

react-native run-android

It will open the android emulator and you can see the swipe components.

Finally, our React Native Swipe Components Example is over.

 

The post React Native Swipe Components Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/08/13/react-native-swipe-components-example-tutorial/feed/ 0
React Native Drawer Navigator Example https://appdividend.com/2018/08/10/react-native-drawer-navigator-example/ https://appdividend.com/2018/08/10/react-native-drawer-navigator-example/#comments Fri, 10 Aug 2018 03:02:27 +0000 http://localhost/wordpress/?p=1461 React Native Drawer Tutorial

React Native Drawer Navigator Example is today’s leading topic. React Native Navigation is a robust library that helps us create Navigation between different screens, Drawer navigation and Tab navigation in our React Native apps. We also use Ionicons to display the icons on the screen. After this example, you can able to create a drawer which will toggle […]

The post React Native Drawer Navigator Example appeared first on AppDividend.

]]>
React Native Drawer Tutorial

React Native Drawer Navigator Example is today’s leading topic. React Native Navigation is a robust library that helps us create Navigation between different screens, Drawer navigation and Tab navigation in our React Native apps. We also use Ionicons to display the icons on the screen. After this example, you can able to create a drawer which will toggle based on the button. Let us start this React Native Drawer Navigator Example by installing React Native on Mac.

If you want to learn more about React Native and Redux then check out this course. The Complete React Native and Redux Course

React Native Drawer Navigator Example

Install React Native using React Native CLI. If you have not installed the React Native CLI then install it globally by the following command.

#1: Install React Native.

Type the following command to install it globally.

sudo npm install -g react-native-cli

Now, create a React Native project using the following command.

react-native init drawer

Go into the project folder.

cd drawer

Install the third-party library using the following command.

yarn add react-native-navigation react-native-vector-icons

Now link these dependencies or configure it with our project using the following command.

react-native link

 

React Native Drawer Navigator Example

You also need to change one thing, if not done correctly.

In Xcode, you will need to edit this file: AppDelegate.m.

Replace all of its code with this reference

Replace @"index.ios" with @"index" if you are using index.js as your entry point instead of index.ios.js and index.android.js (it is the default since React Native 0.49).

#2: Create a HomeScreen for our application.

Inside the root folder, create one folder called screens. Inside that folder, create one file called HomeScreen.js. Write the following code inside it.

// HomeScreen.js

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

export default class HomeScreen extends Component {

  onButtonPress = () => {
    console.log('Button Pressed!!')
  }

  render() {
    return (
      <View>
        <Text>Home Screen</Text>
        <Button title="Tab Navigation" onPress = { this.onButtonPress } />
      </View>
    );
  }
}

Okay, now inside App.js file write the following code. We need to register the Navigation component.

// App.js

import { Navigation } from 'react-native-navigation';

import HomeScreen from './screens/HomeScreen';

Navigation.registerComponent('drawer.HomeScreen', () => HomeScreen);

Navigation.startSingleScreenApp({
  screen: {
    screen: 'drawer.HomeScreen',
    title: 'Home'
  }
});

#3: Create an index.ios.js file inside the root.

We have already one file comes with a project called the index.js, but we will not use it. Instead, we create iOS specifically that is why its name is index.ios.js.

Write the following line of code inside the index.ios.js file.

// index.ios.js

import App from './App';

#4: Create one more screen.

Inside screens folder, create one file called AnalyticsScreen.js and add the following code inside it.

// AnalyticsScreen.js

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

export default class AnalyticsScreen extends Component {
  render() {
    return (
      <View>
        <Text> Your AnalyticsScreen </Text>
      </View>
    )
  }
}

Now, register this screen inside App.js file.

// App.js

import { Navigation } from 'react-native-navigation';

import HomeScreen from './screens/HomeScreen';
import AnalyticsScreen from './screens/AnalyticsScreen';

Navigation.registerComponent('drawer.HomeScreen', () => HomeScreen);
Navigation.registerComponent('drawer.AnalyticsScreen', () => AnalyticsScreen);

Navigation.startSingleScreenApp({
  screen: {
    screen: 'drawer.HomeScreen',
    title: 'Home'
  }
});

#5: Create a SideDrawer Component.

Inside the screens folder, create one file called SideDrawer.js and add the following content.

This is the component we will display as a sidebar drawer.

// SideDrawer.js

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

export default class SideDrawer extends Component {
    render() {
      return (
        <View style = { styles.container }>
          <Text> SideDrawer </Text>
        </View>
      )
    }
}

const styles = StyleSheet.create({
  container: {
    marginTop: 22,
    backgroundColor: 'white',
    width: Dimensions.get("window").width * 0.8
  }
});

Now, we need one configuration file called startMainTab.js file inside screens folder. So let us create it.

// startMainTab.js

import { Navigation } from 'react-native-navigation';
import Icon from 'react-native-vector-icons/Ionicons'; 

const startTabs = () => {
  Promise.all([
    Icon.getImageSource("ios-share-alt", 30),
    Icon.getImageSource("ios-menu", 30)
  ]).then(sources => {
    Navigation.startTabBasedApp({
      tabs: [
        {
          screen: 'drawer.AnalyticsScreen',
          label: 'Analytics',
          title: 'Analytics',
          icon: sources[0],
          navigatorButtons: {
            leftButtons: [
              {
                icon: sources[1],
                title: "Menu",
                id: 'sideDrawerToggle'
              }
            ]
          }
        }
      ],
      drawer: {
        left: {
          screen: 'drawer.SideDrawer'
        }
      }
    });
  });
}

export default startTabs;

So, here we have used one tab screen called AnalyticsScreen.js. Also, we have attached the Drawer to it.

Now, we need to import this inside HomeScreen.js file. So when the user clicks on the button, we can see the AnalyticsScreen tab.

// AnalyticsScreen.js

import React, { Component } from 'react';
import { View, Text,Button } from 'react-native';
import startMainTab from './startMainTab';

export default class HomeScreen extends Component {

  onButtonPress = () => {
    startMainTab();
  }

  render() {
    return (
      <View>
        <Text>Home Screen</Text>
        <Button title="Tab Navigation" onPress = { this.onButtonPress } />
      </View>
    );
  }
}

Okay, now run the application using the following command.

react-native run-ios

Now, you will see your Home Screen like below image.

 

React Native Drawer Example Tutorial

Now, click on the Tab Navigation and you will see the following screen.

 

React Native Navigation Drawer Tutorial

#6: Finishing the Drawer.

Inside the AnalyticsScreen.js file, we need to add an event that can toggle the Drawer. So final file looks like below.

// AnalyticsScreen.js

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

export default class AnalyticsScreen extends Component {

  constructor(props) {
    super(props);
    this.props.navigator.setOnNavigatorEvent(this.onNavigatorEvent);
  }

  onNavigatorEvent = event => {
    if(event.type === "NavBarButtonPress") {
      if(event.id === "sideDrawerToggle") {
        this.props.navigator.toggleDrawer({
          side: 'left'     
        });
      }
    }
  }

  render() {
    return (
      <View>
        <Text> Your AnalyticsScreen </Text>
      </View>
    )
  }
}

Also, register the SideDrawer.js inside App.js file.

// App.js

import { Navigation } from 'react-native-navigation';

import HomeScreen from './screens/HomeScreen';
import AnalyticsScreen from './screens/AnalyticsScreen';
import SideDrawer from './screens/SideDrawer';

Navigation.registerComponent('drawer.HomeScreen', () => HomeScreen);
Navigation.registerComponent('drawer.SideDrawer', () => SideDrawer);
Navigation.registerComponent('drawer.AnalyticsScreen', () => AnalyticsScreen);

Navigation.startSingleScreenApp({
  screen: {
    screen: 'drawer.HomeScreen',
    title: 'Home'
  }
});

Save the file and go to the Simulator and refresh the screen. Now you can able to toggle the Drawer.

 

Drawer Navigation in React Native

Finally, we have achieved our Goal and created working Drawer. React Native Drawer Navigator Example is over. Thanks for taking. I have put this code on Github.

Github Code

The post React Native Drawer Navigator Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/08/10/react-native-drawer-navigator-example/feed/ 1
React Native Tab View Example Tutorial https://appdividend.com/2018/08/08/react-native-tab-view-example-tutorial/ https://appdividend.com/2018/08/08/react-native-tab-view-example-tutorial/#comments Wed, 08 Aug 2018 01:37:01 +0000 http://localhost/wordpress/?p=1447 React Native Tabs Component Example

React Native Tab View Example Tutorial is today’s leading topic. Recently I needed tabbed navigation for a React Native app I’m working on. So in this example, I will show you how you can create a tab navigation system in React Native. First, we register the different screens using Navigation object and then define this function startTabBasedApp(params) which contains […]

The post React Native Tab View Example Tutorial appeared first on AppDividend.

]]>
React Native Tabs Component Example

React Native Tab View Example Tutorial is today’s leading topic. Recently I needed tabbed navigation for a React Native app I’m working on. So in this example, I will show you how you can create a tab navigation system in React Native. First, we register the different screens using Navigation object and then define this function startTabBasedApp(params) which contains an object as an argument. We have seen the startSingleScreenApp(params) in the previous example; now we will navigate through multiple screens using Tab Navigation. Now, start this example by installing, the React Native.

If you want to learn more about React Native and Redux then check out this course. The Complete React Native and Redux Course

React Native Tab View Example Tutorial

Okay, now we install the React Native using the React Native CLI. If you have not installed previously then install it globally using the following command.

#1: Setup React Native For iOS device.

Type the following command.

npm install -g react-native-cli

Create a new project using the following command.

react-native init rncreate

Now go inside that project folder.

cd rncreate

Type the following command to install the libraries.

yarn add react-native-navigation@latest react-native-vector-icons

So, we have used the react-native-navigation and react-native-vector-icons.

Now, we need to configure this library. Remember, we will test our project on iOS simulators and not Android simulators. So this demo is oriented explicitly for the iOS development.

#2: Configure both the libraries inside XCode.

Okay, now we need to open the project in the XCode. So open the Xcode and open the folder rncreate >> ios inside XCode. Now, we need to add the libraries from node_modules. Perform the following steps for react-native-navigation configuration.

#Configure react-native-navigation

  1. In Xcode, in Project Navigator (left pane), right-click on the Libraries Add files to [project name]. Add ./node_modules/react-native-navigation/ios/ReactNativeNavigation.xcodeproj (screenshots)

  2. In Xcode, in Project Navigator (left pane), click on your project (top), then click on your target row (on the “project and targets list”, which is on the left column of the right pane) and select the Build Phases tab (right pane). In the Link Binary With Libraries section add libReactNativeNavigation.a (screenshots)
  3. In Xcode, in Project Navigator (left pane), click on your project (top), then click on your project row (on the “project and targets list”) and select the Build Settings tab (right pane). In the Header Search Paths section add $(SRCROOT)/../node_modules/react-native-navigation/ios. Make sure on the right to mark this new path recursive (screenshots)
  4. In Xcode, you will need to edit this fileAppDelegate.m.

    Replace all of its code with this reference

    Replace @"index.ios" with @"index" if you are using index.js as your entry point instead of index.ios.js and index.android.js (it is the default since React Native 0.49).

#Configure react-native-vector icons.

  1. Open the iOS folder inside Xcode, and you will find the directory structure like this.

         React Native Tab View Example Tutorial

Here, you can see one folder called Libraries. Right click on that folder and click on the Add Files to rncreate.

It will open up the file browser. Now browse to the project root’s node_modules folder and navigate to the react-native-vector-icons and inside that Add the RNVectorIcons.xcodeproj.

2) The second step is inside Xcode, click on the root folder, you will get something like below.

 

React Native Tabs Example Tutorial

Here, I have already clicked on the Build Phases, but you need to click the Build Phases tab, and here also we need to add the files. Search for the file called libRNVectoricons.a and add the file and you are done.

#3: Create screens.

Now, you can close the XCode and open the project in your favorite editor. Inside the root folder, create one folder called screens and inside that create two files named following.

  1. InboxScreen.js
  2. OutboxScreen.js

Write the following code inside both of the files. Remember, when we navigate between different tabs, we will see these screens.

// InboxScreen.js

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

export default class InboxScreen extends Component {
  render() {
    return (
      <View>
        <Text> This is Inbox(4) </Text>
      </View>
    )

  }
}

Also, write the following code inside OutboxScreen.js file.

// OutboxScreen.js

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

export default class OutboxScreen extends Component {
  render() {
    return (
      <View>
        <Text> This is sent messages(10) </Text>
      </View>
    )

  }
}

In the same folder means inside screens folder, we also need to create one more file, which will be our main tab file. Let us call that file startMainTab.js and add the following code inside it. 

// startMainTab.js

import { Navigation } from 'react-native-navigation';

const startTabs = () => {
  Navigation.startTabBasedApp({
    tabs: [
      {
        screen: 'rncreate.InboxScreen',
        label: 'Inbox',
        title: 'Inbox'
      },
      {
        screen: 'rncreate.OutboxScreen',
        label: 'Outbox',
        title: 'Outbox'
      }
    ]
  });
}

export default startTabs;

Here, we need to define all the screens, which has a tab layout. So we have created two screens till now. So we have passed the two items as an argument.

Write the following code inside the startMainTab.js file.

// startMainTab.js

import { Navigation } from 'react-native-navigation';

const startTabs = () => {
  Navigation.startTabBasedApp({
    tabs: [
      {
        screen: 'rncreate.InboxScreen',
        label: 'Inbox',
        title: 'Inbox'
      },
      {
        screen: 'rncreate.OutboxScreen',
        label: 'Outbox',
        title: 'Outbox'
      }
    ]
  });
}

export default startTabs;

Here, we have destructured the Navigation object from react-native-navigation.  Also called the startTabBasedApp() function on that object. It takes an object which consists of an array of different screens.

#4: Create a HomeScreen.

Now, inside the screens folder, create one file called HomeScreen.js. Here we need to import that startMainTab.js file.

// HomeScreen.js

import React, { Component } from 'react';
import { View, Text,Button } from 'react-native';
import startMainTab from './startMainTab';

export default class HomeScreen extends Component {

  onButtonPress = () => {
    startMainTab();
  }

  render() {
    return (
      <View>
        <Text>Home Screen</Text>
        <Button title="Tab Navigation" onPress = { this.onButtonPress } />
      </View>
    );
  }
}

When the application starts, we will see this screen and also one button titled Tab Navigation.

#5: Register all three screens.

Inside App.js file, we need to replace the code with the following code. App.js file is inside root folder.

// App.js

import { Navigation } from 'react-native-navigation';
import HomeScreen from './screens/HomeScreen';
import InboxScreen from './screens/InboxScreen';
import OutboxScreen from './screens/OutboxScreen';

Navigation.registerComponent('rncreate.HomeScreen', () => HomeScreen);
Navigation.registerComponent('rncreate.InboxScreen', () => InboxScreen);
Navigation.registerComponent('rncreate.OutboxScreen', () => OutboxScreen);

Navigation.startSingleScreenApp({
  screen: {
    screen: 'rncreate.HomeScreen',
    title: 'Home'  
  }
});

So, when the application starts, the first screen will be the HomeScreen. If we create 10-20 screens for our application, then we need to register all the screens over here.

Now, we will not use index.js file which comes with React Native by default, instead of that, we will create our index.ios.js file for specifically iOS development. So inside the root, create an index.ios.js file and add the following code inside it.

// index.ios.js

import App from './App';

We need to import the App.js file, and that is it. Nothing more. If you have configured the settings of third-party libraries correctly then compile our project using the following command.

react-native run-ios

You will see this first screen.

Tab Navigation In React Native

 

Now click on the Tab Navigation button, and you will see the following screen.

 

React Native Tabs Navigation Tutorial

Here in the bottom, you can see the two tabs.

  1. Inbox
  2. Outbox

You can click on it, and it will display the content accordingly. So here are basic React Native Tab View Example  Tutorial is over.

#6: Add React Native Vector Icons.

Inside screens >> startMainTab.js file, we need to add the ionicons. So our final file looks like this.

// startMainTab.js

import { Navigation } from 'react-native-navigation';
import Icon from 'react-native-vector-icons/Ionicons'; 

const startTabs = () => {
  Promise.all([
    Icon.getImageSource("md-map", 30),
    Icon.getImageSource("ios-share-alt", 30)
  ]).then(sources => {
    Navigation.startTabBasedApp({
      tabs: [
        {
          screen: 'rncreate.InboxScreen',
          label: 'Inbox',
          title: 'Inbox',
          icon: sources[0]
        },
        {
          screen: 'rncreate.OutboxScreen',
          label: 'Outbox',
          title: 'Outbox',
          icon: sources[1]
        }
      ]
    });
  });
}

export default startTabs;

Finally, we have added icons to our application, and our React Native Tab View Example is over.

 

The post React Native Tab View Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/08/08/react-native-tab-view-example-tutorial/feed/ 1
Native Navigation using React Native Navigation Example https://appdividend.com/2018/08/07/react-native-navigation-example/ https://appdividend.com/2018/08/07/react-native-navigation-example/#comments Tue, 07 Aug 2018 07:58:38 +0000 http://localhost/wordpress/?p=1441 React Native Navigation Example

Native Navigation using React Native Navigation Example is today’s leading topic. For this tutorial, we use the library called React Native Navigation. You can find the documentation here. We have already seen the Navigation in React Native using React Navigation library in our previous tutorials, but now we are using React Native Navigation library, not React Navigation library. […]

The post Native Navigation using React Native Navigation Example appeared first on AppDividend.

]]>
React Native Navigation Example

Native Navigation using React Native Navigation Example is today’s leading topic. For this tutorial, we use the library called React Native Navigation. You can find the documentation here. We have already seen the Navigation in React Native using React Navigation library in our previous tutorials, but now we are using React Native Navigation library, not React Navigation library. So let us start our example by installing React Native.

If you want to learn more about React Native and Redux then check out this course. The Complete React Native and Redux Course

Native Navigation using React Native Navigation

We start this tutorial by installing React Native using React Native CLI.

#1: Install React Native.

If you have not installed React Native CLI, then you can install it using the following command.

npm install -g react-native-cli

Now, create the project using the following command.

react-native init rncreate

Go into the project folder.

cd rncreate

To open the project inside iOS Simulator, type the following command.

react-native run-ios

Now, install the Navigation library using the following command.

yarn add react-native-navigation@latest

# or

npm install react-native-navigation@latest --save

#2: Configure Navigation inside an iOS project.

Okay, now we need to configure the React Native Navigation for our project. So open the rncreate >> ios folder inside XCode because now we need to add some files.

You need to follow the below instructions.

  1. In Xcode, in Project Navigator (left pane), right-click on the Libraries > Add files to [project name]. Add ./node_modules/react-native-navigation/ios/ReactNativeNavigation.xcodeproj (screenshots)

  2. In Xcode, in Project Navigator (left pane), click on your project (top), then click on your target row (on the “project and targets list”, which is on the left column of the right pane) and select the Build Phases tab (right pane). In the Link Binary With Libraries section add libReactNativeNavigation.a (screenshots)
  3. In Xcode, in Project Navigator (left pane), click on your project (top), then click on your project row (on the “project and targets list”) and select the Build Settings tab (right pane). In the Header Search Paths section add $(SRCROOT)/../node_modules/react-native-navigation/ios. Make sure on the right to mark this new path recursive (screenshots)
  4. In Xcode, you will need to edit this file: AppDelegate.m.

    Replace all of its code with this reference

    Replace @"index.ios" with @"index" if you are using index.js as your entry point instead of index.ios.js and index.android.js (it is the default since React Native 0.49).

So, now if you have followed the above steps, you can run the project inside simulator successfully.

#3: Create a single Screen.

Create one folder inside root called screens and inside that, create one file called Home.js and add the following code inside it.

// Home.js

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

export default class HomeScreen extends Component {
  render() {
    return (
      <View>
        <Text>Home Screen</Text>
      </View>
    );
  }
}

Now, we already have an index.js file, but it won’t be needed anymore. So instead of that file, create one new file inside root called index.ios.js and add the following code.

Write the following one line of code.

import App from './App';

And now, write the following code inside App.js file.

// App.js

import { Navigation } from 'react-native-navigation';
import HomeScreen from './screens/Home';

Navigation.registerComponent('rncreate.HomeScreen', () => HomeScreen);

Navigation.startSingleScreenApp({
  screen: {
    screen: 'rncreate.HomeScreen',
    title: 'Home'  
  }
});

Save the file and go to the iOS Simulator.

If changes are not refected then you need to restart the server.

Native Navigation using React Native Navigation Example

 

So, now single-screen navigation is complete for iOS development. In the further tutorial, we see how we can navigate to the different screens using Tab navigator.

The post Native Navigation using React Native Navigation Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/08/07/react-native-navigation-example/feed/ 1
React Native Redux Example Tutorial From Scratch https://appdividend.com/2018/08/04/react-native-redux-example-tutorial/ https://appdividend.com/2018/08/04/react-native-redux-example-tutorial/#comments Sat, 04 Aug 2018 10:15:14 +0000 http://localhost/wordpress/?p=1433 React Native Redux Tutorial Demo

React Native Redux Example Tutorial From Scratch is today’s leading topic. Redux is a standalone state management library, which can be used with any library or framework. If your background is React developer, then you have used the Redux library with React. The primary use of Redux is that we can use one application state as […]

The post React Native Redux Example Tutorial From Scratch appeared first on AppDividend.

]]>
React Native Redux Tutorial Demo

React Native Redux Example Tutorial From Scratch is today’s leading topic. Redux is a standalone state management library, which can be used with any library or framework. If your background is React developer, then you have used the Redux library with React. The primary use of Redux is that we can use one application state as a global state and interact with the state from any react component is very easy whether they are siblings or parent-child. Now, let us start the React Native Redux Example Tutorial by installing React Native on Mac first.

If you want to learn more about React Native and Redux then check out this course. The Complete React Native and Redux Course

React Native Redux Example Tutorial

We start our project by installing React Native CLI globally on the Mac. You can skip the following command if you have already installed.

#1: Install React Native.

Type the following command.

npm install -g react-native-cli

Okay, now for creating a new application, type the following command.

react-native init rncreate
cd rncreate

Now, after installing, we need to open this application in the two different Simulators.

For testing on iOS simulator, type the following command.

react-native run-ios

If you have configured XCode correctly, then one iOS device will pop up as well as development server will also start.

To open the project inside Android Simulator type the following command.

react-native run-android

Install the redux and react-redux library using the following command.

yarn add redux react-redux

# or

npm install redux react-redux --save

#2: Add Textbox and Button into the App.js.

Okay, so we will add a text box and button to add places. So let us add the TextInput and Button.  Also, we will add flexbox layout. Write the following code inside the App.js file.

// App.js

import React, {Component} from 'react';
import { StyleSheet, View, TextInput, Button } from 'react-native';

export default class App extends Component {

placeSubmitHandler = () => {
    console.log("Submitted");	
}

render() {
   return (
    <View style={ styles.container }>
       <View style = { styles.inputContainer }>
        <TextInput
           placeholder = "Seach Places"
           style = { styles.placeInput }
        ></TextInput>
        <Button title = 'Add' 
            style = { styles.placeButton }
            onPress = { this.placeSubmitHandler }
        />
        </View>
    </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 30,
    justifyContent: 'flex-start',
    alignItems: 'center',
  },
  inputContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    width: '100%'
  },
  placeInput: {
    width: '70%'
  },
  placeButton: {
    width: '30%'
  },
  listContainer: {
    width: '100%'
  }
});

#3: Define the state and input handler.

Okay, now we need a state to manage. So we define the initial state like following.

// App.js

state = {
   placeName: '',
   places: []
}

placeSubmitHandler = () => {
    console.log("Submitted");	
}

#4: Create the following folders inside Root.

Create the following folders.

  1. actions
  2. reducers
  3. components

Inside the actions folder, create one file called types.js. Add the following line inside types.js.

export const ADD_PLACE = 'ADD_PLACE'

Action type is the reducer’s operation type. Based on the action type the reducer case will be executed, and we modify the state in such a way that it remains pure. So we create a copy of the existing state and return a new state.

Now, create one more file called place.js in the same directory.

// place.js

import { ADD_PLACE } from './types';

export const addPlace = placeName => {
  return {
    type: ADD_PLACE,
    payload: placeName
  }
}

The addPlace() function returns an action. Now based on that action, reducers function’s case is executed.

But, we need to connect this action to our App.js component somehow. Otherwise, we can not add the data into the Redux store. Also, we need to first create a store. But before, we also need to create a reducer function. So, first create a reducer then create a store and then connect the React Native application to the Redux store.

#5: Create a Reducer function.

Inside reducers function, create one file called placeReducer.js. Add the following code inside it.

// placeReducer.js

import { ADD_PLACE } from '../actions/types';

const initialState = {
  placeName: '',
  places: []
};

const placeReducer = (state = initialState, action) => {
  switch(action.type) {
    case ADD_PLACE:
      return {
        ...state,
        places: state.places.concat({
          key: Math.random(),
          value: action.payload
        })
      };
    default:
      return state;
  }
}

export default placeReducer;

So, here, we have defined the function called placeReducer that accepts the two arguments.

  1. state
  2. action

The first time, it will take the initial state of our application, and then we pass whatever argument, it takes that argument and operates based on the case execution. The second argument is action, which consists of type and payload. The payload is the place name, we have entered inside the text box. So it adds the text box’s value inside places array.

Remeber here; we have returned a new state and not existing state. So we have modified the state in the pure manner and not existing state.

#6: Create a Redux Store.

Inside the root folder, create one file called store.js and add the following code.

// store.js

import { createStore, combineReducers } from 'redux';
import placeReducer from './reducers/placeReducer';

const rootReducer = combineReducers({
  places: placeReducer
});

const configureStore = () => {
  return createStore(rootReducer);
}

export default configureStore;

Here, we have created the redux store and passed the reducer to that store. The combineReducer function combines all the different reducers into one and forms the global state. So this is the global state of our whole application.

#7: Pass the Store to the React Native app.

Inside the root folder, you will find one file called index.js and inside that file add the following code.

// index.js

import { AppRegistry } from 'react-native';
import React from 'react';
import App from './App';
import { name as appName } from './app.json';
import { Provider } from 'react-redux';

import configureStore from './store';

const store = configureStore()

const RNRedux = () => (
  <Provider store = { store }>
    <App />
  </Provider>
)

AppRegistry.registerComponent(appName, () => RNRedux);

It is almost the same as React web application, in which we pass the Provider as a root element and pass the store and then via react-redux’s connect() function, we can connect the any react component to redux store.

#8: Connect React Native app to Redux store.

Finally, we connect our App.js component to the Redux store. For that, we need the connect() function from the react-redux library.

// App.js

import React, { Component } from 'react';
import { StyleSheet, View, TextInput, Button, FlatList } from 'react-native';
import ListItem from './components/ListItem';
import { connect } from 'react-redux';
import { addPlace } from './actions/place';

class App extends Component {

  state = {
    placeName: '',
    places: []
  }

  placeSubmitHandler = () => {
    if(this.state.placeName.trim() === '') {
      return;
    }
    this.props.add(this.state.placeName);
}

placeNameChangeHandler = (value) => {
  this.setState({
    placeName: value
  });    
}

placesOutput = () => {
   return (
    <FlatList style = { styles.listContainer }
      data = { this.props.places }
      keyExtractor={(item, index) => index.toString()}
      renderItem = { info => (
        <ListItem 
          placeName={ info.item.value }
        />
      )}
    />
  )
}

render() {
  return (
    <View style={ styles.container }>
      <View style = { styles.inputContainer }>
        <TextInput
          placeholder = "Seach Places"
          style = { styles.placeInput }
          value = { this.state.placeName }
          onChangeText = { this.placeNameChangeHandler }
        ></TextInput>
        <Button title = 'Add' 
          style = { styles.placeButton }
          onPress = { this.placeSubmitHandler }
        />
        </View>
        <View style = { styles.listContainer }>
          { this.placesOutput() }
        </View>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    paddingTop: 30,
    justifyContent: 'flex-start',
    alignItems: 'center',
  },
  inputContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    width: '100%'
  },
  placeInput: {
    width: '70%'
  },
  placeButton: {
    width: '30%'
  },
  listContainer: {
    width: '100%'
  }
});

const mapStateToProps = state => {
  return {
    places: state.places.places
  }
}

const mapDispatchToProps = dispatch => {
  return {
    add: (name) => {
      dispatch(addPlace(name))
    }
  }
}

export default connect(mapStateToProps, mapDispatchToProps)(App)

Here, when we click the add button, we get the textbox value and then send it to the action with that value. Now that action returned the object with the action type and payload and based on the type the reducer will be executed and add that values inside the store.

Now, if the store’s values are changed, then we need to update the UI based on the new values. That is why the mapStateToProps function is created. So, when the store’s places array get the new value, render function executed again and update the UI.

The mapDispatchToProps function helps us to connect our application to the required action, so that action then further executed by a reducer and change the application state.

Also, inside the components folder, create one file called ListItem.js and add the following code inside it.

// ListItem.js

import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';

const ListItem = (props) => {
    return (
      <TouchableOpacity>
        <View style = { styles.listItem }>
          <Text>{ props.placeName }</Text>
        </View>
      </TouchableOpacity>
    );
}

const styles = StyleSheet.create({
  listItem: {
    width: '100%',
    padding: 10,
    marginBottom: 10,
    backgroundColor: '#eee'
  }
});

export default ListItem;

This component receives the properties from the parent component and displays the data in the proper format. Save the file and go to your Simulators and refresh the screen.

React Native Redux Example Tutorial From Scratch

 

Finally, React Native Redux Example Tutorial From Scratch is over. Thanks for taking.

The post React Native Redux Example Tutorial From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/08/04/react-native-redux-example-tutorial/feed/ 20
React Native Modal Example | Tutorial https://appdividend.com/2018/08/02/react-native-modal-example-tutorial/ https://appdividend.com/2018/08/02/react-native-modal-example-tutorial/#comments Thu, 02 Aug 2018 01:54:22 +0000 http://localhost/wordpress/?p=1423 React Native Modal Tutorial

React Native Modal Example is today’s leading topic. In this demo, we will see how we can display the Modal and show the data inside that Modal. For this tutorial, we use React Native component called Modal to display the image and text. It is a straightforward demo, but very useful React Native Modal Tutorial. So […]

The post React Native Modal Example | Tutorial appeared first on AppDividend.

]]>
React Native Modal Tutorial

React Native Modal Example is today’s leading topic. In this demo, we will see how we can display the Modal and show the data inside that Modal. For this tutorial, we use React Native component called Modal to display the image and text. It is a straightforward demo, but very useful React Native Modal Tutorial. So let us dive into it.

If you want to learn more about React Native and Redux then check out this course. The Complete React Native and Redux Course

React Native Modal Example

Okay, first let us install React Native Project.

#1: Install React Native on Mac.

If you have not installed React Native CLI globally then install it using the following command.

npm install -g react-native-cli

Okay, now for creating a new application, type the following command.

react-native init rncreate
cd rncreate

Now, after installing, we need to open this application in the two different Simulators.

For testing on iOS simulator, type the following command.

react-native run-ios

Open the Project in your favorite editor.

code .

#2: Add a Button.

We will display the two things inside the Modal.

  1. Text
  2. Image

So inside the root, create one folder called assets and inside that create one folder called images and add an image from your local machine and copy the image in this folder.

Okay, now Add the Button and Image inside Container View. Type the following code inside App.js.

// App.js

import React, { Component } from 'react';
import Krunal from './assets/images/Krunal.jpg';
import { View, Button, StyleSheet } from 'react-native';

export default class App extends Component {

  render() {
    	return (
        <View style = { styles.container }>
          <Button 
            onPress = { () => console.log('Button Pressed') }
            title = "Open Modal"
            color = "orange">
          </Button>
        </View>
      )
    }
}

const styles = StyleSheet.create({
  container: {
    marginTop: 300,
  }
});

So, here we have added one Button, and also, we have imported the Image file. Right now, we have not used yet, but we will use in a minute. 

Our goal is when the User clicks the button, Modal will pop up otherwise it will not pop up, and we can’t see it. So, now we import one more component and pass the Image and Text as a prop to that component.

Also, by default Modal is always open, so we need to handle it our way. That is why we need the state which we can control, and ultimately we control the Modal.

#3: Create DisplayModal.js file.

Now, create one folder inside root called components and inside that create one file called DisplayModal.js and add the following code.

// DisplayModal.js

import React from 'react'
import { Modal, View, Image, Text, StyleSheet } from 'react-native';

const DisplayModal = (props) => (
  <Modal visible={ props.display } animationType = "slide" 
         onRequestClose={ () => console.log('closed') }>>
    <View>
      <Image 
        source = { props.image } 
        style = { styles.image } />
      <Text style = { styles.text }>
        { props.data }
      </Text>
    </View>
  </Modal>
)

const styles = StyleSheet.create({
  image: {
    marginTop: 20,
    marginLeft: 90,
    height: 200,
    width: 200
  },
  text: {
    fontSize: 20,
    marginLeft: 150
  }
})

export default DisplayModal;

DisplayModal is a static component, and it has nothing to do with State. So I have used as a functional component. It just accepts the props and displays in the styled form.

You can note that we have used Modal’s visible property. So when it is true, we can see the Modal otherwise we don’t see the Modal. Thus it is controlled by the Parent component, and in our case it is App.js.

So when the User clicks, we change the State of the display property inside App.js to true, and now we can see the Modal.

Now, write the following code inside an App.js file.

// App.js

import React, { Component } from 'react';
import Krunal from './assets/images/Krunal.jpg';
import { View, Button, StyleSheet } from 'react-native';
import DisplayModal from './components/DisplayModal';

export default class App extends Component {

  state = {
    display: false
  }

  triggerModal() {
    this.setState(prevState => {
      return {
        display: true
      }
    });
  }

	render() {
    	return (
        <View style = { styles.container }>
          <Button 
            onPress = { () => this.triggerModal() }
            title = "Open Modal"
            color = "orange">
          </Button>
          <DisplayModal 
            image = { Krunal }
            data = "Krunal"
            display = { this.state.display }
          />
        </View>
      )
  	}
}

const styles = StyleSheet.create({
  container: {
    marginTop: 300,
  }
});

So, here, we have defined the one state called display, and by default it is false. When the user clicks on the button, it will change to true, and we can see the Modal will popup.

React Native Modal Example | Tutorial

 

#4: Modal Properties.

You can find out more about Modal Properties on this Link.

Here, we have used one Modal property called animationType.

animationType

It has the following values.

  1. slide:  slides in from the bottom.
  2. fade:  fades into view.
  3. none:  appears without an animation.

We have used the slide, but you can try to fade and see how it can change the layout animation effect.

Visible

The visible property accepts two arguments.

  1. true
  2. false

If it is true, then it will be visible inside the screen otherwise not. We have passed the property of visible inside Modal when the button is clicked.

Finally, React Native Modal Example | Tutorial is over.

The post React Native Modal Example | Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/08/02/react-native-modal-example-tutorial/feed/ 6
React Native Create Delete Functionality From Scratch https://appdividend.com/2018/07/30/react-native-create-delete-functionality/ https://appdividend.com/2018/07/30/react-native-create-delete-functionality/#respond Mon, 30 Jul 2018 14:56:22 +0000 http://localhost/wordpress/?p=1403 React Native CRUD Example

React Native Create Delete Functionality From Scratch is today’s leading topic. We build a simple functionality where users can add and remove places client side. It does not affect the server side because there is no backend. But you will learn how you can create simple clientside create and delete the data in the application. We […]

The post React Native Create Delete Functionality From Scratch appeared first on AppDividend.

]]>
React Native CRUD Example

React Native Create Delete Functionality From Scratch is today’s leading topic. We build a simple functionality where users can add and remove places client side. It does not affect the server side because there is no backend. But you will learn how you can create simple clientside create and delete the data in the application. We will test both on Android and iOS Simulators. So to get started, React Native Create Delete Functionality. Let us started.

If you want to learn more about React Native and Redux then check out this course. The Complete React Native and Redux Course

React Native Create Delete Functionality

We start our project by installing React Native CLI globally on the Mac. You can skip the following command if you have already installed.

#1: Install React Native.

Type the following command.

npm install -g react-native-cli

Okay, now for creating a new application, type the following command.

react-native init rncreate

 

React Native Create Delete Functionality From Scratch

Now, after installing, we need to open this application in the two different Simulators.

For testing on iOS simulator, type the following command.

react-native run-ios

If you have configured XCode correctly, then one iOS device will pop up as well as development server will also start.

React Native Simulator

 

To open the project inside Android device type the following command.

react-native run-android

Also, you need to install Android Studio and then create a virtual device.

If you have found the error like following.

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring project ‘:app‘.
> SDK location not found. Define location with sdk.dir in the local.properties file or with an ANDROID_HOME environment variable.

Then the solution is the following.

Inside the Android folder, create a new file called local.properties and add the following code. Here, you can use your username, and I am using Mac.

sdk.dir = /Users/your username/Library/Android/sdk

Now, again run the above command and shall fix the problem.

React Native Create Delete Functionality

 

 

You can also use an expo for this application. If you do not know anything about the expo, then please check out my this How To Setup React Native Using Expo.

#2: Add Textbox and Button into the App.js.

Okay, so we will add a text box and button to add places. So let us add the TextInput and Button.  Also, we will add flexbox layout. Write the following code inside the App.js file.

// App.js

import React, {Component} from 'react';
import { StyleSheet, View, TextInput, Button } from 'react-native';

export default class App extends Component {

placeSubmitHandler = () => {
    console.log("Submitted");	
}

render() {
   return (
	<View style={ styles.container }>
	   <View style = { styles.inputContainer }>
		<TextInput
		   placeholder = "Seach Places"
		   style = { styles.placeInput }
		></TextInput>
		<Button title = 'Add' 
			style = { styles.placeButton }
			onPress = { this.placeSubmitHandler }
		/>
	    </View>
	</View>
    );
  }
}

const styles = StyleSheet.create({
	  container: {
    	  paddingTop: 30,
    	  justifyContent: 'flex-start',
    	  alignItems: 'center',
      },
      inputContainer: {
	  flexDirection: 'row',
	  justifyContent: 'space-between',
	  alignItems: 'center',
	  width: '100%'
      },
      placeInput: {
	  width: '70%'
      },
      placeButton: {
	  width: '30%'
      }
});

Here is the output on both of the devices.

React Native CRUD Tutorial

 

#3: Define the state and input handler.

Okay, now we need a state to manage. So we define the initial state like following.

// App.js

state = {
   placeName: '',
   places: []
}

placeSubmitHandler = () => {
    console.log("Submitted");	
}

So, we have taken placeName to display the value inside text input and places array on which we loop through and show all the places in FlatList.

// App.js

import React, {Component} from 'react';
import { StyleSheet, View, TextInput, Button } from 'react-native';

export default class App extends Component {

state = {
    placeName: '',
    places: []
}

placeSubmitHandler = () => {
    if(this.state.placeName.trim() === '') {
	return;
    }
    this.setState(prevState => {
      return {
	        places: prevState.places.concat({
		key: Math.random(), 
		value: prevState.placeName
	   })
       }
   });	
}

placeNameChangeHandler = (value) => {
  this.setState({
      placeName: value
    });    
}

render() {
   return (
	<View style={ styles.container }>
	   <View style = { styles.inputContainer }>
		<TextInput
		   placeholder = "Seach Places"
		   style = { styles.placeInput }
                   value = { this.state.placeName }
		   onChangeText = { this.placeNameChangeHandler }
		></TextInput>
		<Button title = 'Add' 
		   style = { styles.placeButton }
		   onPress = { this.placeSubmitHandler }
		/>
	    </View>
	</View>
    );
  }
}

So, when you start typing inside TextInput, the state is updated, and you can see the values inside text input, and when you press the add button, it checks if the value is empty or not. If not empty then add the values inside places array. It is a very familiar practice in React.js.

#4: Display the Data in the FlatList.

Inside root, create one folder called components and inside create one file called ListItem.js and add the following code inside that file.

// ListItem.js

import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';

const ListItem = (props) => {
    return (
        <TouchableOpacity>
            <View style = { styles.listItem }>
                <Text>{ props.placeName }</Text>
            </View>
        </TouchableOpacity>
    );
}

const styles = StyleSheet.create({
    listItem: {
        width: '100%',
        padding: 10,
        marginBottom: 10,
        backgroundColor: '#eee'
    }
});

export default ListItem;

We have created this file because we will render this component and display the list. Here, we have passed the props as an argument, so we can access the place values through props and display it in the proper format.

Okay, now we need to include the FlatList inside App.js file and render the above component.

// App.js

import React, {Component} from 'react';
import { StyleSheet, View, TextInput, Button, FlatList } from 'react-native';
import ListItem from './components/ListItem';

export default class App extends Component {

state = {
    placeName: '',
    places: []
}

placeSubmitHandler = () => {
    if(this.state.placeName.trim() === '') {
	return;
    }
    this.setState(prevState => {
      return {
	        places: prevState.places.concat({
		key: Math.random(), 
		value: prevState.placeName
	   })
       }
   });
   this.setState({
      placeName: ''
   });	
}

placeNameChangeHandler = (value) => {
  this.setState({
      placeName: value
    });    
}

placesOutput = () => {
   return (
	<FlatList style = { styles.listContainer }
	   data = { this.state.places }
	   keyExtractor={(item, index) => index.toString()}
           renderItem = { info => (
		  <ListItem 
		        placeName={ info.item.value }
		   />
	     )}
	/>
    )
}

render() {
   return (
	<View style={ styles.container }>
	   <View style = { styles.inputContainer }>
		<TextInput
		   placeholder = "Seach Places"
		   style = { styles.placeInput }
                   value = { this.state.placeName }
		   onChangeText = { this.placeNameChangeHandler }
		></TextInput>
		<Button title = 'Add' 
		   style = { styles.placeButton }
		   onPress = { this.placeSubmitHandler }
		/>
	    </View>
            <View style = { styles.listContainer }>
		{ this.placesOutput() }
	    </View>
	</View>
    );
  }
}

const styles = StyleSheet.create({
      container: {
    	  paddingTop: 30,
    	  justifyContent: 'flex-start',
    	  alignItems: 'center',
      },
      inputContainer: {
	  flexDirection: 'row',
	  justifyContent: 'space-between',
	  alignItems: 'center',
	  width: '100%'
      },
      placeInput: {
	  width: '70%'
      },
      placeButton: {
	  width: '30%'
      },
      listContainer: {
	  width: '100%'
      }
});

 

React Native FlatList ScrollView Example

#5: Implement Delete Functionality.

So, when the user touches the list, it will remove the element from an array. We have already used the TouchableOpacity. So it fades the particular item and removes from the list permanently.

For that, we need to add the onPress() event to the TouchableOpacity. So we can pass the index value and filter out the data based on that index.

So, we need to add the event inside first App.js file, and then through props, we can access that inside ListItem.js file.

// App.js

import React, {Component} from 'react';
import { StyleSheet, View, TextInput, Button, FlatList } from 'react-native';
import ListItem from './components/ListItem';

export default class App extends Component {

state = {
    placeName: '',
    places: []
}

placeSubmitHandler = () => {
    if(this.state.placeName.trim() === '') {
	return;
    }
    this.setState(prevState => {
      return {
	        places: prevState.places.concat({
		key: Math.random(), 
		value: prevState.placeName
	   })
       }
   });
   this.setState({
      placeName: ''
   });	
}

placeNameChangeHandler = (value) => {
  this.setState({
      placeName: value
    });    
}

placesOutput = () => {
   return (
	<FlatList style = { styles.listContainer }
	   data = { this.state.places }
	   keyExtractor={(item, index) => index.toString()}
           renderItem = { info => (
		  <ListItem 
		        placeName={ info.item.value }
                        onItemPressed={() => this.onItemDeleted(info.item.key)}
		   />
	     )}
	/>
    )
}

onItemDeleted = (key) => {
   this.setState(prevState => {
      return {
         places: prevState.places.filter(place => {
            return place.key !== key;
	  })
	}
    })
}

render() {
   return (
	<View style={ styles.container }>
	   <View style = { styles.inputContainer }>
		<TextInput
		   placeholder = "Seach Places"
		   style = { styles.placeInput }
                   value = { this.state.placeName }
		   onChangeText = { this.placeNameChangeHandler }
		></TextInput>
		<Button title = 'Add' 
		   style = { styles.placeButton }
		   onPress = { this.placeSubmitHandler }
		/>
	    </View>
            <View style = { styles.listContainer }>
		{ this.placesOutput() }
	    </View>
	</View>
    );
  }
}

const styles = StyleSheet.create({
      container: {
    	  paddingTop: 30,
    	  justifyContent: 'flex-start',
    	  alignItems: 'center',
      },
      inputContainer: {
	  flexDirection: 'row',
	  justifyContent: 'space-between',
	  alignItems: 'center',
	  width: '100%'
      },
      placeInput: {
	  width: '70%'
      },
      placeButton: {
	  width: '30%'
      },
      listContainer: {
	  width: '100%'
      }
});

Okay, so we have defined the onDeleteItem() function, and also we have passed that as props to the Child Element. Now, we need to modify the ListItem.js component.

// ListItem.js

import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';

const ListItem = (props) => {
    return (
        <TouchableOpacity onPress={ props.onItemPressed }>
            <View style = { styles.listItem }>
                <Text>{ props.placeName }</Text>
            </View>
        </TouchableOpacity>
    );
}

const styles = StyleSheet.create({
    listItem: {
        width: '100%',
        padding: 10,
        marginBottom: 10,
        backgroundColor: '#eee'
    }
});

export default ListItem;

Here, we have defined the onPress event. So when the user presses the list item, it will get filtered out.

So, we have a working demo of React Native Create Delete Functionality. Thanks for taking.

The post React Native Create Delete Functionality From Scratch appeared first on AppDividend.

]]>
https://appdividend.com/2018/07/30/react-native-create-delete-functionality/feed/ 0
React Native Animation Tutorial With Example https://appdividend.com/2018/07/23/react-native-animation-tutorial-with-example/ https://appdividend.com/2018/07/23/react-native-animation-tutorial-with-example/#respond Mon, 23 Jul 2018 17:28:45 +0000 http://localhost/wordpress/?p=1361 React Native Animations With Example From Scratch

React Native Animation Tutorial With Example is the today’s leading topic. The recommended way to animate in React Native for most cases is by using the Animated API. It is a basic demo app. in which we move the square from top to bottom with animation. This example is Kickstarter for React Native Animation, and complex cases will be […]

The post React Native Animation Tutorial With Example appeared first on AppDividend.

]]>
React Native Animations With Example From Scratch

React Native Animation Tutorial With Example is the today’s leading topic. The recommended way to animate in React Native for most cases is by using the Animated API. It is a basic demo app. in which we move the square from top to bottom with animation. This example is Kickstarter for React Native Animation, and complex cases will be covered in the future. But right now, we start our project by installing the React Native using Expo.

If you are not familiar with the expo, then I am suggesting you that first check this tutorial on How To Setup React Native Using ExpoIt will help you to set up expo and you will up and running with React Native on your physical device.

Also, you can check out the below course to learn React Native From Scratch.
React Native – The Practical Guide

React Native Animation Tutorial With Example

Now, if you do not want to use expo and you have to create a project and test in Simulator or Emulator, then you can type the following command to install React Native on Mac. If you are using Expo, then you can skip the first step.

#1: Install React Native.

Type the following command.

react-native init AnimationApp

Go into the project.

cd AnimationApp

Now to open the app inside our iOS Simulator, type the following command.

react-native run-ios --simulator="iPhone X"

 

React Native Animation Tutorial With Example

#2: Animations With React Native.

There are two kinds of Animation system in React Native.

  1. Layout Animations
  2. Animated

#Layout Animations

In Layout Animations system, it is easy to set up, and we do not have much control. Some parts of our application will also be animated, whether we have intended or not. So there is not much control over all of our components. So we do not use this kind of Animation.

#Animated

It is more complicated to set up, but it is perfect to create complex animations, and it allows us to handle the Gesture animations. The Animated library is designed to make animations fluid, powerful, and easy to build and maintain. Animated focuses on declarative relationships between the inputs and outputs, with configurable transforms in between, and simple start/stop methods to control time-based animation execution.

Three questions describe the whole animation system.

  1. Where is our primary object or item right now? So it’s X and Y position in the current scenario.
  2. Where is the Element moving to? So the place where we need to shift our element.
  3. Which element is we are going to move?

The answers to all above questions define the Animation system.

So the Animated Module consists of three things.

  1. Values: The Current XY values of an element
  2. Types: Which type of animation we will use like Spring, Timing, Decay
  3. Components: On which components like Text, View, Image.

#3: Create Square Animation.

Now, open the project folder inside your favorite editor. I am recommending that you should start using VSCode if you are not using already. For JavaScript development, it is the best open source and free editor out there.

Okay, now, create one folder in root called components and inside this folder, create a component called  SquareAnimation.js and add the following code in it.

// SquareAnimation.js

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

class SquareAnimation extends Component {

    componentWillMount() {
        this.position = new Animated.ValueXY(0, 0);
        Animated.spring(this.position, {
            toValue: { x: 225, y: 575 }
        }).start();
    }

    render() {
        return (
            <Animated.View style={ this.position.getLayout() }>
                <View style={ styles.square } />
            </Animated.View>
        );
    }
}

const styles = {
    square: {
        width: 120,
        height: 120,
        backgroundColor: '#00BCD4'
    }
}
export default SquareAnimation;

So, here, First I have defined the View, and that view’s shape is Square based on its styles. So we are moving the square from top to bottom and see how basic animation works in React Native.

On componentWillMount() lifecycle method, we have set the Square position to 0, and then we start immediately moving our object to values of X = 225 and Y = 575.

Also, we have wrapped the View with the Animated.View. So we can see the animation from  (0, 0) to (225, 575).

Animated.spring() function will take the first argument as an initial position and then takes the second argument to how far we need to move that object, and then we are called the start function().

Here, we are moving the Square View. So we have wrapped  Squared View (View which has style square)with the Animated.View.

So, with the help of this.position.getLayout(), we can fetch the style of the previous and current location of the object, and we can see a complete animation.

We take as many elements inside <Animated.view>. As of right now, we have just picked the Square. But you can add as many items as you want.

Now, finally Add the SquareAnimation.js component inside App.js file.

// App.js

import React, { Component } from 'react';
import { View } from 'react-native';
import SquareAnimation from './components/SquareAnimation';

export default class App extends Component {
  render() {
    return (
      <View>
        <SquareAnimation />
      </View>
    );
  }
}

Save the file and see the iPhone X Simulator. Refresh the Simulator again and again, and you can see that the Square is moving from top to bottom as per defined positions.

React Native Animations Example

 

So this example is the Very Easy Implementation of React Native Animation Tutorial. We will create a Gesture based animation in the future post. So right now that is it for the React Native Animation Tutorial.

The post React Native Animation Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/07/23/react-native-animation-tutorial-with-example/feed/ 0
How To Setup React Native Using Expo https://appdividend.com/2018/07/19/how-to-setup-react-native-using-expo/ https://appdividend.com/2018/07/19/how-to-setup-react-native-using-expo/#respond Thu, 19 Jul 2018 16:26:51 +0000 http://localhost/wordpress/?p=1352 React Native Expo App Tutorial

How To Setup React Native Using Expo is the main topic, we will discuss today. React Native is quite a famous library to make a cross mobile applications. Today, we install React Native using Expo client. Through Expo client, we can run our mobile app into our actual devices and not in Simulators or Emulators. So […]

The post How To Setup React Native Using Expo appeared first on AppDividend.

]]>
React Native Expo App Tutorial

How To Setup React Native Using Expo is the main topic, we will discuss today. React Native is quite a famous library to make a cross mobile applications. Today, we install React Native using Expo client. Through Expo client, we can run our mobile app into our actual devices and not in Simulators or Emulators. So we can test runtime our application into our real Android or iOS devices. For this to work, the first requirement is we do need a high-speed connection otherwise it won’t work or throw an error like Switched to a LAN URL because the tunnel appears to be down. Only devices in the same network can access the app. You can restart the project to try reconnecting.

In this post, we will configure Expo XDE into the Mac as well as install Expo client on to the Android and iOS devices and then connect through our development server. So when we change anything in our React Native code, it will reload our actual devices’ application, and we can see an instant output of our code into our actual devices and not in any emulators or simulators. Although if you have not robust internet connectivity, then you can always go for emulators or simulators.

Also, you can check out the below course to learn React Native From Scratch.
React Native – The Practical Guide

How To Setup React Native Using Expo

Okay, now our first step is to install Expo XDE on Mac. I am using Mac so I will show you how you can install it on a mac. There is already instruction about Windows installation on their documentation.

#1: Install Expo XDE on Mac

Go to this link. Here you can find Expo XDE based on your PC Operating System. Mine is Mac so that I will install the DMG file. It will take some minutes to install it.

Okay, after downloading, we need to install it on our Mac and move the Expo XDE to our Applications.

Then launch the Expo XDE.

#2: Register yourself to Expo XDE.

Now, we need to register our self to that application. So next time we need to log in to our account, and we can start playing around with our app on any Android or iOS devices.

You can register on this link. Also, do not forget to verify your email and you are good to go.

Now, you also need to sign in to your Expo XDE application already opened in your mac with the recently registered email and password.

#3: Create a new Project.

After logged in, you need to create a new project. So the dialog box looks like this.

How To Setup React Native Using Expo

 

 

Here, you need to choose a blank view, and also you need to give you a project name and its path. So at that path original React Native project is created.

Okay, now you need to open your mobile expo app and also login with same credentials as we have applied on the desktop app and login into our expo app.

Now, switch to the desktop expo xde and upper right corner there are three buttons.

  1. Publish
  2. Share
  3. Device

Click to share, and you can see like this.

 

React Native Expo Tutorial With Example

Now, we need to scan this barcode from our mobile app as there is already the option of scanning. You can also type your email or phone number to sent a link. I am doing this using Barcode.

After scanning, we can see in the desktop expo client starts the development server and compile our javascript bundle. After the completion, you can see a Mac Expo XDE like this.

React Native Expo App Tutorial

 

Here, you might face a problem like below.

Switched to a LAN URL because the tunnel appears to be down. Only devices in the same network can access the app. You can restart the project to try reconnecting.

The problem is not with any configurations, but with the Slow Internet Connectivity. You can always restart the server to see if now everything works great.

If everything works great, then you can see on your mobile that we know the app is running. You can see on both Android or iOS devices. You can also open your project in your editor and modify some code and depend on your net speed, it will reflect on your mobile devices. Cool!!! Very Cool.

Now, when you exit all of the applications and go for the next day, just select the existing project and start the server, and you are good to go, of course, you need to select the project from the mobile device as well via expo client. So it is very easy.

This kind of development is convenient when we are dealing with a complex project which uses React Native animations. So we can test our progress instantly.

You can find the link for expo clients for both Android and iOS devices here.

For iOS: https://itunes.apple.com/app/apple-store/id982107779

For Android: https://play.google.com/store/apps/details?id=host.exp.exponent&referrer=www

You can also run the Emulator or Simulator for React Native projects.

To use that, we need to hit the Device button at the upper right corner inside our Expo XDE mac application and in that you need to choose for Android or iOS device. You need to configure both the devices using XCode or Android Studio, and you can see all of your developments inside your virtual devices.

So that is it for How To Setup React Native Using Expo client.

The post How To Setup React Native Using Expo appeared first on AppDividend.

]]>
https://appdividend.com/2018/07/19/how-to-setup-react-native-using-expo/feed/ 0
React Native Firebase Example https://appdividend.com/2018/04/23/react-native-firebase-example-from-scratch/ https://appdividend.com/2018/04/23/react-native-firebase-example-from-scratch/#comments Mon, 23 Apr 2018 04:12:43 +0000 http://localhost/wordpress/?p=556 Firebase React Native For Beginners

React Native Firebase Example is the today’s topic. Getting started with React Native and Firebase. I was first skeptical about Firebase, but after using it, it seems like the Firebase may be able to speed up widespread mobile and web app development. In a traditional mobile or web app progress when you’re building something other. Also, you can check out the below course […]

The post React Native Firebase Example appeared first on AppDividend.

]]>
Firebase React Native For Beginners

React Native Firebase Example is the today’s topic. Getting started with React Native and Firebase. I was first skeptical about Firebase, but after using it, it seems like the Firebase may be able to speed up widespread mobile and web app development. In a traditional mobile or web app progress when you’re building something other.

Also, you can check out the below course to learn React Native From Scratch.
React Native – The Practical Guide

React Native Firebase Example

Let us start our example by installing the React Native Project.

Step 1: Install React Native.

Install the React Native CLI using the following command.

# for mac users

sudo npm install -g react-native-cli

# for windows users: open cmd on admin mode and type 

npm install -g react-native-cli

Now, create our project using the following command.

react-native init RNFbase

Go into that project.

cd RNFbase

Start the package server and simulator using the following command.

react-native run-ios --simulator="iPhone X"

You will see this screen.

React Native Firebase Example

 

If you are facing Yellow warnings like isMounted(…) is deprecated in plain javascript react classes” error with this dependencies then add the following code inside App.js file.

// App.js

import { YellowBox } from 'react-native';

YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader']);

Step 2: Install Firebase Dependency.

Type the following command to install the Firebase.

yarn add firebase

# or

npm install firebase --save

Step 3: Create required directories.

In the root of the project, make the one directory called src.  In that directory, create three folders.

  1. screens
  2. components
  3. services

Screens folder contains the screens which we need to display to the User. In our case, we will create three screens.

Components folder contains the mobile components we will use to display the data from the API.

Services folder contains network files. It is the files in which we will write the code to make a request to the server and get the response from the server.

Step 4: Create two screens.

Inside src  >>  screens folder, create the following files.

  1.  Home.js
  2. AddItem.js
  3. ListItem.js

Home.js is the pure React Native class.

// Home.js

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

export default class Home extends Component {
  render() {
    return (
      <View>
        <Text>Home Screen</Text>
      </View>
    )
  }
}

Same do for the AddItem.js file.

// AddItem.js

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

export default class AddItem extends Component {
  render() {
    return (
      <View>
        <Text>Add Item</Text>
      </View>
    )
  }
}

Also, same for ListItem.js file.

// ListItem.js

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

export default class ListItem extends Component {
  render() {
    return (
      <View>
        <Text>List Item</Text>
      </View>
    )
  }
}

Step 5: Integrate React Native Navigation.

We need to install React Navigation library to transition the app from one screen to another screen.

yarn add react-navigation

# or

npm install react-navigation --save

Now, after installing, go to the App.js file. We will use StackNavigator to transit from one to another screen. It is routing for our application.

// App.js

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import Home from './src/screens/Home';
import AddItem from './src/screens/AddItem';
import ListItem from './src/screens/ListItem';
import { YellowBox } from 'react-native';

YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader']);

const AppNavigator = StackNavigator({
  HomeScreen: { screen: Home },
  AddItemScreen: { screen: AddItem },
  ListItemScreen: { screen: ListItem }
});

export default class App extends Component {
  render() {
    return (
      <AppNavigator />
    );
  }
}

We have included both the screen here and passed that screen into the StackNavigator function. It will handle the transition of our screens. HomeScreen displays like the following.

React Native Firebase Tutorial

 

Step 6: Create a database in Firebase console.

Go to the https://firebase.google.com and login to your Google account and create a new project.

Now, in React Native, we fetch the database config as a web app, so go to your web app section and get the config object. We need to connect our app to the firebase.

Create a new folder, inside src folder, called config and in that, make a new file called db.js. Write the following code in it.

// db.js

import Firebase from 'firebase';
 let config = {
    apiKey: "",
    authDomain: "",
    databaseURL: "",
    projectId: "",
    storageBucket: "",
    messagingSenderId: ""
  };
let app = Firebase.initializeApp(config);
export const db = app.database();

You have your configuration values, so you need to copy the whole config from your firebase app.

Step 7: Create a form the add the data.

Write the following code inside AddItem.js file.

// AddItem.js

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

export default class AddItem extends Component {
  constructor(props) {
      super(props);
      this.state = {
        name: '',
        error: false
      }
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleChange(e) {
      this.setState({
        name: e.nativeEvent.text
      });
    }
    handleSubmit() {
      console.log(this.state.name)
    }
  render() {
    return (
      <View style={styles.main}>
        <Text style={styles.title}>Add Item</Text>
        <TextInput
              style={styles.itemInput}
              onChange={this.handleChange}
            />
        <TouchableHighlight
                style = {styles.button}
                underlayColor= "white"
                onPress = {this.handleSubmit}
              >
              <Text
                  style={styles.buttonText}>
                  Add
              </Text>
            </TouchableHighlight>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  main: {
    flex: 1,
    padding: 30,
    flexDirection: 'column',
    justifyContent: 'center',
    backgroundColor: '#2a8ab7'
  },
  title: {
    marginBottom: 20,
    fontSize: 25,
    textAlign: 'center'
  },
  itemInput: {
    height: 50,
    padding: 4,
    marginRight: 5,
    fontSize: 23,
    borderWidth: 1,
    borderColor: 'white',
    borderRadius: 8,
    color: 'white'
  },
  buttonText: {
    fontSize: 18,
    color: '#111',
    alignSelf: 'center'
  },
  button: {
    height: 45,
    flexDirection: 'row',
    backgroundColor:'white',
    borderColor: 'white',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    marginTop: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  }
});

So, I have defined some basic style of our form. So our AddItem.js screen looks like this.

Firebase React Native Example

 

Step 8: Create a service file to add data to Firebase.

Inside services folder, create one file called ItemService.js.

// ItemService.js

import { db } from '../config/db';

export const addItem =  (item) => {
    db.ref('/items').push({
        name: item
    });
}

Now, we need to import this services file into AddItem.js file.

// AddItem.js

import React, { Component } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TextInput,
  TouchableHighlight,
  AlertIOS
} from 'react-native';
import { addItem } from '../services/ItemService';

export default class AddItem extends Component {
  constructor(props) {
      super(props);
      this.state = {
        name: ''
      }
      this.handleChange = this.handleChange.bind(this);
      this.handleSubmit = this.handleSubmit.bind(this);
    }
    handleChange(e) {
      this.setState({
        name: e.nativeEvent.text
      });
    }
    handleSubmit() {
      addItem(this.state.name);
      AlertIOS.alert(
        'Item saved successfully'
       );
    }
  render() {
    return (
      <View style={styles.main}>
        <Text style={styles.title}>Add Item</Text>
        <TextInput
              style={styles.itemInput}
              onChange={this.handleChange}
            />
        <TouchableHighlight
                style = {styles.button}
                underlayColor= "white"
                onPress = {this.handleSubmit}
              >
              <Text
                  style={styles.buttonText}>
                  Add
              </Text>
            </TouchableHighlight>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  main: {
    flex: 1,
    padding: 30,
    flexDirection: 'column',
    justifyContent: 'center',
    backgroundColor: '#2a8ab7'
  },
  title: {
    marginBottom: 20,
    fontSize: 25,
    textAlign: 'center'
  },
  itemInput: {
    height: 50,
    padding: 4,
    marginRight: 5,
    fontSize: 23,
    borderWidth: 1,
    borderColor: 'white',
    borderRadius: 8,
    color: 'white'
  },
  buttonText: {
    fontSize: 18,
    color: '#111',
    alignSelf: 'center'
  },
  button: {
    height: 45,
    flexDirection: 'row',
    backgroundColor:'white',
    borderColor: 'white',
    borderWidth: 1,
    borderRadius: 8,
    marginBottom: 10,
    marginTop: 10,
    alignSelf: 'stretch',
    justifyContent: 'center'
  }
});

I have imported addItem function and passed our textbox value to that function and also imported the AlertIOS component to display the alert box saying that our data has been successfully saved.

React Native Firebase save data

 

Also, you can see the data in the Firebase.

Firebase Tutorial

 

Step 9: Display Items.

Write the following code inside ListItem.js file.

// ListItem.js

import React, { Component } from 'react';
import { View, Text, StyleSheet} from 'react-native';
import ItemComponent from '../components/ItemComponent';

import { db } from '../config/db';

let itemsRef = db.ref('/items');

const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      backgroundColor: '#B6A6BB',
    }
  })

export default class ListItem extends Component {

    state = {
        items: []
    }

    componentDidMount() {
        itemsRef.on('value', (snapshot) => {
            let data = snapshot.val();
            let items = Object.values(data);
            this.setState({items});
         });
    }
    
    render() {
        return (
            <View style={styles.container}>
                {
                    this.state.items.length > 0
                    ? <ItemComponent items={this.state.items} />
                    : <Text>No items</Text>
                }
            </View>
        )
    }
}

Okay, now we need to create ItemComponent.js file inside src  >>  components folder. It will display our data from the Firebase.

// ItemComponent.js

import React, { Component } from 'react';
import {  View, Text, StyleSheet} from 'react-native';
import PropTypes from 'prop-types';

const styles = StyleSheet.create({
    itemsList: {
        flex: 1,
        flexDirection: 'column',
        justifyContent: 'space-around',
    },
    itemtext: {
        fontSize: 24,
        fontWeight: 'bold',
        textAlign: 'center',
    }
});

export default class ItemComponent extends Component {

  static propTypes = {
      items: PropTypes.array.isRequired
  };

  render() {
    return (
      <View style={styles.itemsList}>
        {this.props.items.map((item, index) => {
            return (
                <View key={index}>
                    <Text style={styles.itemtext}>{item.name}</Text>
                </View>
            )
        })}
      </View>
    );
  }
}

 

React Native Fetch Data

This is not pretty much design but, I just wanted you to guys see how it can connect with Firebase and we can fetch the data and display that on the Screen. That is the main moto of this Tutorial.

That is it, I know there is lots of stuff we can fix this but, we will tackle one by one in the future tutorials.

So, React Native Firebase Example Tutorial is over. Thanks for taking.

The post React Native Firebase Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/04/23/react-native-firebase-example-from-scratch/feed/ 10