How to Setup, Build and Deploy Native Apps with Vue

How to Setup, Build and Deploy Native Apps with Vue

This Vue-Native tutorial explains how to Setup, Build and Deploy Native Apps with Vue. Vue-Native is a framework that lets us build native Vue apps, inspired by the React-Native API. It is inspired by the React-native API, hence it gives a developer the ability to build cross platform applications in Vue.js using React Native’s robust system.

Vue-Native is a framework written by GeekyAnts, it is a framework built to deliver cross platform mobile native applications. It is inspired by the React-native API, hence it gives a developer the ability to build cross platform applications in Vue.js using React Native’s robust system.

Table of Contents

  • Prerequisites
  • Getting started
  • Testing on mobile
  • Creating a Giphy application
  • App component
  • Creating the gif item component
  • Header component
  • Deploying the application
  • Summary

Vue Native was originally a fork from React-vue, a compiler that gave developers that ability to write Vue and React in the same codebase. In this article, we’ll build a simple application to introduce the APIs and components available in Vue native.

We’ll be building a simple application that fetches the trending Gifs on Giphy, using the Giphy API. We’ll also display the Gif and details about it using components like ScrollView, Text, Image etc.

Prerequisites

To follow this tutorial, you’ll need to have Node > 6.0 installed. You’ll also need any of the package managers, NPM (this comes packaged with Node) or Yarn.

Basic knowledge of Javascript and Vue is also required. You can follow the official Vue documentation here to get up to speed.

Getting started

Before we get started, we’ll need to setup the project and install project dependencies. We’ll be making use of Vue native CLI to bootstrap our application. There’s also an installation option using Create React Native App, this option is longer but you can find the instructions here.

First, install the Vue Native CLI by running the following command:

yarn global add vue-native-cli
//  or
 npm install -g vue-native-cli

Then initialize a new project by running the following command:

vue-native init vue-gifs

Running this command will bootstrap a Create React Native App application using the Expo CLI.

At the time of writing the Vue Native CLI needs the React Native version_ 0.55.4_ and expo version 29.0.0, so update your package.json to set these versions. We’ll also add commands to build for ios and android platforms by updating the scripts object.

//package.json

{
  "name": "vue-gifs",
  "main": "node_modules/expo/AppEntry.js",
  "private": true,
  "scripts": {
    ...
    "build:ios": "expo build:ios",
    "build:android": "expo build:android",
  },
  "dependencies": {
    "expo": "^29.0.0",
    ...
    "react-native": "0.55.4",
    ...
  },
  "devDependencies": {
    "babel-preset-expo": "^4.0.0",
    ...
  }
}

Then update the sdkVersion in the app.json file to match the expo version. Open the app.json file and update it like the snippet below:

{
  "expo": {
    "name": "vue-gifs",
    "description": "This project is really great.",
    ...
    "sdkVersion": "29.0.0",
    ...
  }
}

Everything else will remain the same. After making these changes, run npm install or yarn to install the required versions for the application. When this is done, run npm start to run the application.

To build and run our application, we’ll be using Expo. Expo is an open source toolchain built around React-native for building Android and iOS applications. It provides access to the system’s functionality like the Camera, Storage etc.

Testing on mobile

To test the application on mobile, the expo-cli provides various methods to test the application. The first is using a URL generated after running the application, this URL can be visited on your mobile browser to test the application.

Run the npm run start-native command within your project folder to run the application using expo. expo typically starts your application on port 19002, visit http://localhost:19002 to view the expo dev tools. Within the dev tools you can send the preview link as an SMS or email to your mobile phone.

You can select any of the three connection options. An external tunnel, LAN or Local connection. For the local connection, your mobile phone and work PC have to be connection to the same network but the tunnel works regardless.

The next method which is the easiest is downloading the Expo mobile app, it can be found on both the Apple App store and the Android Play store. On iOS, after installing the app, open up your camera and scan the barcode above to run your application. While on Android, you can use the Expo app to scan the barcode and run the application.

Run any of the following command to test on either platforms:

npm start

After starting the application, scan the barcode and view the application on the expo app. You should see a view similar to the screenshot below:

Let’s see the other methods we can test the application on mobile. The next option for testing on a mobile device is using an emulator or simulator. Using Android studio or Xcode, you can boot emulators or simulators for their respective platforms. Download and install the tool for the platform of choice, Xcode for iOS and Android studio for Android. After installation, run any of the following commands to start the application:

npm run ios
  # OR
npm run android
Creating a Giphy application

To get started consuming the Giphy API, you’ll need to log in to your Giphy account, create one if you haven’t already. The next step is to create an app on the developer platform. On your developer account dashboard, there’s a Create App button, click it and fill in the details about your application.

After creating the app, your new application should be displayed on your dashboard with an API key, this key will be used when making requests to Giphy

To make requests to the Giphy service, we’ll make use of their Javascript SDK. Run the following command to install the package:

npm install --save giphy-js-sdk-core

Now we can go ahead and consume the APIs with the help of this SDK.

App component

Our application is a simple one that displays the trending gifs on the Giphy platform. Using the Giphy API, we’ll get the associated gif image, title and type from the returned data. The data will be displayed using some of the components provided by vue-native. Open the App.vue file in the root folder and update it like the snippet below:

<template>
    <view>
        <scroll-view class="scroll-view">
           //Todo: Create gif item and header
           <view class="loading-container" :style="{flex: 1, justifyContent: 'center'}" v-if="loading">
              <activity-indicator size="large" color="#0000ff"></activity-indicator>
            </view>         </scroll-view>
    </view>
</template>
<script>
  import Giphy from 'giphy-js-sdk-core';
  const client = Giphy('GIPHY_API_KEY');

  export default {
    name: 'App',
    data() {
      return {
        gifs: [],
        loading: true,
      };
    },
    async created() {
      const response = await client.trending('gifs', {limit: 20});
      this.gifs = response.data;
    },
  };
</script>
<style>
    .scroll-view {
        padding-top: 20px;
        padding-bottom: 30px;
    }
    .loading-container {
        height: 600px;
    }
</style>

In the snippet above, the App component renders a scrollview component that houses the components elements. It only displays an activityindicator, this will be replaced by the list of gif when the call to the API is complete.

Also, we instantiate the Giphy client using the API key obtained from the developers dashboard and replace the placeholder string with the API key. Calling the trending method makes a call to the Giphy trending endpoint. The first provided parameter is gifs, this indicates which trending items should be returned, gifs or stickers. The second parameter is an object providing optional parameters like the limit, offset, rating and fmt (format).

We’ll just be providing a limit parameter, limiting the results to 20 items. This call is made in the created lifecycle of the component. Next, we’ll create the gif item to render the returned results.

After reloading, the application should display the activity indicator:

Creating the gif item component

Each gif item will be displayed using a View component, the View component is an important building block, it supports layout using flexbox, styling and accessibility. Each item will display the gif, title and type. Create a folder components in the root folder. Within the components directory, create a named GifItem.vue and update it with the code below:

// GifItem.vue

<template>
  <view class="container">
    <image class="img" :source="{uri: `${gif.images.original.url}`}" style="max-width:100%;"/>
    <text class="title">{{titleCase(gif.title)}}</text>
  </view>
</template>
<script>
export default {
  name: "GifItem",
  props: ["gif"],
  methods: {
    titleCase(text) {
      const textArray = text.split(" ");
      return textArray
        .map(text => {
          const trimmedText = text.trim();
          return `${trimmedText[0].toUpperCase()}${trimmedText.slice(1)}`;
        })
        .join(" ");
    }
  }
};
</script>
<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 30px;
  position: relative;
}
.img {
  height: 200px;
  width: 300px;
}
.title {
  font-size: 14px;
  font-weight: 500;
  margin-top: 7px;
}
</style>

Using the Image component, we can display the source of each gif and the Text component to display the gif title. The Image component takes a source prop which is an object with a uri property.

The titleCase method takes the title of each gif and returns the text in title case, capitalizing the first letter of each word in the text. The GifItem component will take a single prop gif.

Let’s update the App.vue file to include the new GifItem. Update the file with the snippet below:

<template>
    <view>
        <scroll-view class="scroll-view">
            <gif-item v-for="gif in gifs" :gif="gif" :key="gif.id" v-if="!loading"/>
            <view class="loading-container" :style="{flex: 1, justifyContent: 'center'}" v-if="loading">
                <activity-indicator size="large" color="#0000ff"></activity-indicator>
            </view>
        </scroll-view>
    </view>
</template>
<script>
  import Giphy from 'giphy-js-sdk-core';
  const client = Giphy('API_KEY');
  import GifItem from './components/GifItem';

  export default {
    name: 'App',
    data() {
      return {
        gifs: [],
        loading: true
      };
    },
    async created() {
      const response = await client.trending('gifs', {limit: 20});
      this.gifs = response.data;
      this.loading = false;
    },
    components: {GifItem}
  };
</script>
<style>
    .scroll-view {
        padding-top: 20px;
        padding-bottom: 30px;
    }
    .loading-container {
        height: 600px;
    }
</style>

When you open the application in the expo app, you’ll see something similar to the screenshot below:

If you can’t see gifs listed, go through the tutorial again to see what you’ve have missed along the way.

Header component

After successfully querying for trending gifs and displaying them using native components, let’s include a header to give the application context. Using the View component, we’ll create an area that will act as the header for our application. Create file called header.vue within the components directory and update it with the code below:

// /components/header.vue
<template>
    <view class="header-container">
        <text class="header">Trending</text>
    </view>
</template>
<script>
  export default {
    name: 'header.vue'
  };
</script>
<style scoped>
    .header-container {
        background-color: rgba(0, 0, 0, 0.05);
        display: flex;
        justify-content: center;
        padding-top: 15px;
        padding-bottom: 15px;
        border-bottom-color: aquamarine;
        border-bottom-width: 1px;
        margin-top: 20px;
    }
    .header {
        font-size: 16px;
        color: black;
        opacity: 0.8;
        font-weight: 600;
        text-align: center;
    }
</style>

Now let’s add the header component to the App component. This will display a simple header at the top of the application. Update the App.vue file to include the Header component:

<template>
    <view>
        <header/>
        <scroll-view class="scroll-view">
            ...
        </scroll-view>
    </view>
</template>
<script>
  import Giphy from 'giphy-js-sdk-core';
  const client = Giphy('TxuQbNU1nyDBwpqrcib61LxmOzsXTPEk');

  import GifItem from './components/GifItem';
  import Header from './components/header';

  export default {
    name: 'App',
    data() {
     ...
    },
    async created() {
      ...
    },
    components: {GifItem, Header}
  };
</script>
<style>
   ...
</style>

After the application refreshes the header will be added to the top of the application.

We’ve been able to achieve a lot of display functionality using the components provided by Vue-native.

Deploying the application

We’ll be deploying our application to the Android Play store. To achieve this, we’ll need to update the app.json to include Android specific properties. Open the app.json file and update the file to include the android field:

{
  "expo": {
    ...
    "android": {
      "package": "com.vue.gifs"
    }
  }
}

The android.package field is a unique value that will represent your package in the app store. You can read more on the package naming convention here. After updating the file, run the npm run build:android command.

This command will present you with a prompt, asking you to provide a keystore or to generate a new one. If you have an existing keystore, you can select this option or let expo generate one for your application.

After completion, a download link will be generated for your application, clicking on this link will be trigger a download for your apk.

To deploy the downloaded APK to the Android Play Store, visit the Play Console to create an account, then you’ll be required to pay a registration fee of $25 before proceeding. When registration is complete, visit this page and follow the steps to upload your application to the Play Store.

Summary

Vue native has provided a solution to build for mobile platforms using Vuejs. It compiles to React and uses components provided by React Native. As as the time of writing, some of it’s components require that you write JSX with the actual React Native components. Since Vue native works with React native, you can follow the official React native documentation. Vue native is still in it’s infant stages and has a lot of potential, it creates an opportunity for Vue.js developers to build cross platform mobile applications. You can view the source code for the demo here.

React's Context API Tutorial: What Context is and How to use it!

React's Context API Tutorial: What Context is and How to use it!

React's Context API has become the state management tool of choice for many, oftentimes replacing Redux altogether. In this tutorial, you'll see an introduction to what Context is and how to use it!

React's Context API has become the state management tool of choice for many, oftentimes replacing Redux altogether. In this quick tutorial, you'll see an introduction to what Context is and how to use it!

Consider this tree, in which the bottom boxes represent separate components:

We can easily add state to the bottom components, but until now the only way to pass data to a component's sibling was to move state to a higher component and then pass it back down to the sibling via props.

If we later find out that the sibling of the component with state also needs the data, we have to lift state up again, and pass it back down:

While this solution does work, problems begin if a component on a different branch needs the data:

In this case, we need to pass state from the top level of the application through all the intermediary components to the one which needs the data at the bottom, even though the intermediary levels don't need it. This tedious and time-consuming process is known as prop drilling.

This is where Context API comes in. It provides a way of passing data through the component tree via a Provider-Consumer pair without having to pass props down through every level. Think of it as the components playing Catch with data - the intermediary components might not even "know" that anything is happening:

To demonstrate this, we will create this funky (and super useful) day-to-night switching image.

If you want to see the full code, be sure to check out the Scrimba playground for this article.

Create Context

To begin, we create a new Context. As we want the entire app to have access to this, we go to index.js and wrap the app in ThemeContext.Provider.

We also pass the value prop to our Provider. This holds the data we want to save. For now, we just hardcode in 'Day'.

import React from "react";
import ReactDOM from "react-dom";
import ThemeContext from "./themeContext";

import App from "./App";

ReactDOM.render(
  <ThemeContext.Provider value={"Day"}>
    <App />
  </ThemeContext.Provider>,
  document.getElementById("root")
);

Consuming Context with contextType

Currently, in App.js, we are simply returning the <Image /> component.

import React from "react";
import Image from "./Image";

class App extends React.Component {
  render() {
    return (
      <div className="app">
        <Image />
      </div>
    );
  }
}

export default App;

Our goal is to use Context to switch the classNames in Image.js from Day to Night, depending on which image we want to render. To do this, we add a static property to our component called ContextType and then use string interpolation to add it to the classNames in the <Image /> component.

Now, the classNames contain the string from the value prop. Note: I have moved ThemeContext into its own file to prevent a bug.

import React from "react";
import Button from "./Button";
import ThemeContext from "./themeContext";

class Image extends React.Component {
  render() {
    const theme = this.context;
    return (
      <div className={`${theme}-image image`}>
        <div className={`${theme}-ball ball`} />
        <Button />
      </div>
    );
  }
}

Image.contextType = ThemeContext;

export default Image;

Context.Consumer

Unfortunately, this approach only works with class-based components. If you've learned about Hooks in React already, you'll know we can do just about anything with functional components these days. So for good measure, we should convert our components into functional components and then use ThemeContext.Consumer component to pass info through the app.

This is done by wrapping our elements in an instance of <ThemeContext.Consumer> and within that (where the children go), providing a function which returns the elements. This uses the "render prop" pattern where we provide a regular function as a child that returns some JSX to render.

import React from "react";
import Button from "./Button";
import ThemeContext from "./themeContext";

function Image(props) {
  // We don't need this anymore
  // const theme = this.context

  return (
    <ThemeContext.Consumer>
      {theme => (
        <div className={`${theme}-image image`}>
          <div className={`${theme}-ball ball`} />
          <Button />
        </div>
      )}
    </ThemeContext.Consumer>
  );
}

// We don't need this anymore
// Image.contextType = ThemeContext;

export default Image;

Note: We also need to wrap the <Button /> component in <ThemeContext.Consumer> - this allows us to add functionality to the button later.

import React from "react";
import ThemeContext from "./themeContext";

function Button(props) {
  return (
    <ThemeContext.Consumer>
      {context => (
        <button className="button">
          Switch
          <span role="img" aria-label="sun">
            🌞
          </span>
          <span role="img" aria-label="moon">
            🌚
          </span>
        </button>
      )}
    </ThemeContext.Consumer>
  );
}

export default Button;

Extract Context Provider

We are currently passing a hard-coded value down through the Provider, however, our goal is to switch between night and day with our button.

This requires moving our Provider to a separate file and putting it in its own component, in this case, called ThemeContextProvider.

import React, { Component } from "react";
const { Provider, Consumer } = React.createContext();

class ThemeContextProvider extends Component {
  render() {
    return <Provider value={"Day"}>{this.props.children}</Provider>;
  }
}

export { ThemeContextProvider, Consumer as ThemeContextConsumer };

Note: the value property is now being handled in the new file ThemeContext.js, and should, therefore, be removed from index.js.

Changing Context
To wire up the button, we first add state to ThemeContextProvider:

import React, { Component } from "react";
const { Provider, Consumer } = React.createContext();

// Note: You could also use hooks to provide state and convert this into a functional component.
class ThemeContextProvider extends Component {
  state = {
    theme: "Day"
  };
  render() {
    return <Provider value={"Day"}>{this.props.children}</Provider>;
  }
}

export { ThemeContextProvider, Consumer as ThemeContextConsumer };

Next, we add a method for switching between day and night:

toggleTheme = () => {
  this.setState(prevState => {
    return {
      theme: prevState.theme === "Day" ? "Night" : "Day"
    };
  });
};

Now we change our value property to this.state.theme so that it returns the info from state.

 render() {
    return <Provider value={this.state.theme}>{this.props.children}</Provider>;
  }
}

Next, we change value to an object containing {theme: this.state.theme, toggleTheme: this.toggleTheme}, and update all the places where we use a single value to look for theme in an object. This means that every theme becomes context and every reference to theme as value becomes context.theme.

Finally, we tell the button to listen for the onClick event and then fire context.toggleTheme - this updates the Consumers which are using the state from the Provider. The code for the button looks like this:

import React from "react";
import { ThemeContextConsumer } from "./themeContext";

function Button(props) {
  return (
    <ThemeContextConsumer>
      {context => (
        <button onClick={context.toggleTheme} className="button">
          Switch
          <span role="img" aria-label="sun">
            🌞
          </span>
          <span role="img" aria-label="moon">
            🌚
          </span>
        </button>
      )}
    </ThemeContextConsumer>
  );
}

export default Button;

Our button now switches the image between night and day in one click!

Context caveats

Like all good things in code, there are some caveats to using Context:

  • Don't use Context to avoid drilling props down just one or two layers. Context is great for managing state which is needed by large portions of an application. However, prop drilling is faster if you are just passing info down a couple of layers.

  • Avoid using Context to save state that should be kept locally. So if you need to save a user's form inputs, for example, use local state and not Context.

  • Always wrap the Provider around the lowest possible common parent in the tree - not the app's highest-level component. No need for overkill.

  • Lastly, if you pass an object as your value prop, monitor performance and refactor as necessary. This probably won't be needed unless a drop in performance is noticeable.

Wrap up

This example is pretty simple and it would probably be easier to put state in the app and pass it down via props. However, it hopefully shows the power of having Consumers which can access data independently of the components above them in the tree.

Happy coding :)

React Fetch API Random User API Example | HTTP Requests in React

React Fetch API Random User API Example | HTTP Requests in React

React Fetch API Random User API Example | HTTP Requests in React

React Fetch API Random User API Example | HTTP Requests in React

How to perform CRUD operations and consume RESTful API using React?

How to perform CRUD operations and consume RESTful API using React?

In this post, we go through a tutorial on how to create a React application that can perform CRUD functions and take in data from a RESTful API. Recently we have experienced rapid growth of mobile, Internet-based communication. We have...

In this post, we go through a tutorial on how to create a React application that can perform CRUD functions and take in data from a RESTful API.

Recently we have experienced rapid growth of mobile, Internet-based communication. We have smartphones, tablets, netbooks, and other connected devices that create a need to serve appropriate content for each specific front-end profile. Also, the Internet is becoming available for new regions and social groups, constantly increasing web traffic. On the other side, users' computers and browsers, and JavaScript itself are getting more and more powerful, providing more possibilities for processing data on the web via the client-side. In this situation, the best solution can often be to send data as the response, instead of sending page content. That is, we don't need to reload the whole page on each request, but send back the corresponding data and let the client (front-end stuff) process the data.

We can develop a backend application exposing a remote API (usually based on the REST protocol) and a front-end (usually JavaScript) application, which communicates with the API and renders all the data on the device.

If backend data is consumed by humans, we need to develop a user interface (UI) to provide the possibility for users to manage the data. Modern web applications should have responsive and friendly UIs, ensuring adequate user experience. Also, modern UIs can be arbitrarily complex, with multi-panel, nested layouts, paging, progress bars, etc. In this case, the component model can be the right solution. React.js is a light-weight JavaScript framework, which is oriented toward the creation of component-based web UIs. React doesn't provide any means for communicating with the backend, but we can use any communication library from inside React components.

Before starting development, we need to set up a React.js development environment.

1. React.js Development Environment Set Up

There are several ways to use React.js. The simplest way is just to include React libraries in the