Categories
React Native Developers React Native Web

React Native Bridge For Android

React Native is developed in such a way that we can create a bridge between the Native Language and the JavaScript code. A bridge is nothing but a way to setup communication between native platform and React Native.

But why do we need it?

Let’s assume you want to reuse some existing Java code or library without having to reimplement it in JavaScript. Yes, you guessed it right, you can use it in your React Native application with the help of Native Bridge. At some point of time, to make a production level application you will most probably need to use Native Bridge.

“As long as we are building our application purely within the framework, we can drive our app with properties and callbacks. But, when we mix React Native and native components, we need some specific, cross-language mechanisms that would allow us to pass information between them.”

What we will learn in this article?

We will separate this article in two parts which are:

  • Native Modules
  • Native UI Components

In this article, we are talking about android only.

Native Modules

A Native Module is just a set of javascript functions that are implemented natively for individual platform. Native Modules are used when React Native doesn’t have that required module yet, or when the native performance is significantly better.

To understand this concept better we will implement a toast mechanism in which the toast would be coming from the native android and we will call it from a button made in React Native. In case you are wondering “what a toast is?”, think of it as an alert message for your app.

Let’s start:

Before you start you should have Android Studio and Node.js installed in your computer.

Open your terminal and follow along

npx react-native init ReactNativeBridgeDemo

cd ReactNativeBridgeDemo

Where ReactNativeBridgeDemo is the folder name which will be created.

You will find a folder named ‘android’ in your project. Open that in Android Studio.

From there go to app> java > com.reactnativebridgedemo

There create two files with names ToastModule.java and MyPackage.java. You will understand in a bit that why we named that that way.

In ToastModule.java write the following code:

package com.reactnativebridgedemo;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import android.widget.Toast;

public class ToastModule extends ReactContextBaseJavaModule {
    //constructor
    public ToastModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }
    //Mandatory function getName that specifies the module name
    @Override
    public String getName() {
        return "ToastModule";
    }
    //Custom function that we are going to export to JS
    @ReactMethod
    public void showToast(String message) {
        Toast.makeText(getReactApplicationContext(), message, Toast.LENGTH_SHORT).show();
    }
}

We have created a ToastModule class which is inherited from ReactContextBaseJavaModule. ReactContextBaseJavaModule requires a function named getName whose purpose is to return the string name of the NativeModule which represents this class in the javascript.

@ReactMethod is used to expose a function in javascript as all functions are not exposed to JavaScript explicitly. These methods are of void return type.

ShowToast is the function we will be calling in react-native javascript code to create a native toast.

The next step in Java is to register the module, if a module is not registered it will not be available from JavaScript.

Now, in the MyPackage.java file, which we have created already, write the following code:

package com.reactnativebridgedemo;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class MyPackage implements ReactPackage  {
    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
    
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Arrays.<NativeModule>asList(
                new ToastModule(reactContext)
        );
    }
}

We Override the createNativeModules function and added the ToastModule object to modules array. It needs to be added here to be available in javascript.

We are going to ignore the createViewManagers function for now as it will be covered in the UI Components part later in this article.

This MyPackage needs to be provided in the getPackages method of MainApplication.java file.

Now, open the MainApplication.java file and just add the following line in the getPackages function.

packages.add(new MyPackage());

just like, @Override

protected List<ReactPackage> getPackages() {
  @SuppressWarnings("UnnecessaryLocalVariable")
  List<ReactPackage> packages = new PackageList(this).getPackages();
  // Packages that cannot be autolinked yet can be added manually here, for example:
  // packages.add(new MyReactNativePackage());
  packages.add(new MyPackage());  //<---- ADD THIS LINE
  return packages;
}

Now, to access the showToast function we made in the ToastModule.java, we will make a button in react-native javascript which on clicking will invoke the showToast function.

This will be done by importing {NativeModule} from ‘react-native’ just like the following code in app.js.import React, {Component} from ‘react’;

import {Button, View} from 'react-native';
import {NativeModules} from 'react-native';
const {ToastModule} = NativeModules;
export default class App extends Component {
  _showToast() {
    ToastModule.showToast('This is a native toast!!');
  }
  render() {
    return (
      <View style={{flex: 1, alignItems: 'center', justifyContent: 'center'}}>
        <Button onPress={this._showToast} title="Toast Btn" />
      </View>
    );
  }
}

This exposes the native ToastModule as a JS module.

On pressing the button the _showToast JS function will be invoked which will call the native showToast function in the ToastModule.js which will take a string which is nothing but the toast message.

Thats It.

Now, you can just start the application by the command:

npx react-native run-android

If it does not start the emulator for some reason, you can directly run it from the Android Studio by clicking the ‘run’ button in the toolbar.

You will be seeing the toast just like this,

The great thing is that we have created a Native Bridge for android. So, this was Native Modules, now let’s head over to the second part of this article which is Native UI Components.

Native UI Components

There are tons of native UI widgets out there ready to be used in the latest apps. Fortunately, we can wrap up these existing components for seamless integration with our React Native application. Without further ado, let’s head over to the practical part.

First, Let’s create a simple SwitchApp example using react-native CLI.

npx react-native init  SwitchApp

cd  SwitchApp

Now, Let’s create a Switch UI component. For that open this SwitchApp project in Android Studio just like we did in the Native Module section.

From there go to app> java > com.switchappand

There create three files with names Switch.java, SwitchManager.java and SwitchPackage.java. You will understand in a bit that why we named that that way.

Now, open the Switch.java file and write the following code:

package com.switchapp;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.widget.Button;
public class Switch extends Button {
    public Switch(Context context) {
        super(context);
        this.setTextColor(Color.BLUE);
        this.setText("This button is made in JAVA");
    }
    public Switch(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public Switch(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
}

Here we have created a Switch java class which is inherited from a Button, and the constructor is overwritten. Button text color and text is also customized.

Now, we need a SwitchManager to expose the Switch.java class. So, write the following code in SwitchManager.java:

package com.switchapp;
import com.facebook.react.uimanager.SimpleViewManager;
import com.facebook.react.uimanager.ThemedReactContext;
public class SwitchManager extends SimpleViewManager<Switch> {
    @Override
    public String getName() {
        return "Switch";
    }
    @Override
    protected Switch createViewInstance(ThemedReactContext reactContext) {
        return new Switch(reactContext);
    }
}

Here, we have inherited SwitchManager class from SimpleViewManager. Native views are created and manipulated by extending ViewManager or more commonly SimpleViewManager. A SimpleViewManager is convenient in this case because it applies common properties such as background color, opacity, and flexbox layout.

We always need this custom Manager which should be inherited from ViewManager or SimpleViewManager.

Every Manager class, should have the following:

  • getName() method, which returns a string name, which we will use to call in javascript.
  • createViewInstance(ThemedReactContext reactContext) method in which we create an instance and return the object.

This SwitchManager will also be used in passing props from React Component.

Now, the next step in Java is to register the module, if a module is not registered it will not be available from JavaScript. This step is very much similar to the step we did in NativeModule section.

Now, in the SwitchPackage.java file, which we have created already, write the following code:

package com.switchapp;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.modules.toast.ToastModule;
import com.facebook.react.uimanager.ViewManager;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class SwitchPackage implements ReactPackage  {
    @Override
    public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
        return Arrays.<ViewManager>asList(
                new SwitchManager()
        );
    }
    @Override
    public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
        return Collections.emptyList();
    }
}

We Override the createViewManagers function and added the SwitchManager object to modules array. It needs to be added here to be available in javascript. That’s why we ignored  createViewManagers in the Native Modules section as it is for the UI components.

This SwitchPackage needs to be provided in the getPackages method of MainApplication.java file.

Now, open the MainApplication.java file and just add the following line in the getPackages function.

packages.add(new SwitchPackage());

just like,

@Override

protected List<ReactPackage> getPackages() {
  @SuppressWarnings("UnnecessaryLocalVariable")
  List<ReactPackage> packages = new PackageList(this).getPackages();
  // Packages that cannot be autolinked yet can be added manually here, for example:
  // packages.add(new MyReactNativePackage());
  packages.add(new SwitchPackage());  //<---- ADD THIS LINE
  return packages;
}

Now to use this UI button, we have just made in Java, in react-native javascript.

This will be done by importing {requireNativeComponent} from ‘react-native’ just like the following code in app.js.

import React, {Component} from ‘react’;

import {StyleSheet, View, requireNativeComponent} from 'react-native';
const Switch = requireNativeComponent('Switch');
export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Switch style={styles.javaBtn} />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'pink',
    alignItems: 'center',
    justifyContent: 'center',
  },
  javaBtn: {
    height: 100,
    width: 300,
    backgroundColor: 'yellow',
  },
});

The requireNativeComponent function takes the name of the native view. In this case, we used the name “Switch” and now <Switch> component is ready to be used. Now we have a button which is made in Java and shown in the app through javascript.

You will be seeing the button just like this,

We have successfully rendered a UI button <Switch> which we made in Java.

Now, we will enhance this component to accept props from the javascript code, which we are going to use the change the color of the button deciding whether the switch is ON or OFF.

First, let’s pass a prop name isTurnedOn in the <Switch> component like:

<Switch style={styles.javaBtn} isTurnedOn={true} />

isTurnedOn will take boolean values which when true, the color of the button will be yellow and when false then the color  would be grey.

Now, open SwitchManager.java and add the following method in the SwitchManager class.

@ReactProp(name="isTurnedOn")
public void setSwitchStatus(Switch switchView, Boolean isTurnedOn) {
    switchView.setIsTurnedOn(isTurnedOn);
}

Properties that are to be reflected in JavaScript needs to be exposed as setter method annotated with @ReactProp (or @ReactPropGroup). Setter method should take view to be updated (of the current view type) as a first argument and property value as a second argument. In the above example, we are calling the setIsTurnedOn method with a boolean value as argument which we got as prop from the react-native javascript code. We will define this method in Switch.java.

Now open Switch.java and update the following code:

package com.switchapp;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.View;
import android.widget.Button;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.RCTEventEmitter;
public class Switch extends Button {

    public Boolean isTurnedOn = false;

    public void setIsTurnedOn (Boolean switchStatus){
        isTurnedOn = switchStatus;
        changeColor();
    }
    public Switch(Context context) {
        super(context);
        this.setTextColor(Color.BLUE);
        this.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                isTurnedOn = !isTurnedOn;
                changeColor();
            }
        });
        changeColor();
    }
    
    private void changeColor() {
        if (isTurnedOn) {
            setBackgroundColor(Color.YELLOW);
            setText("I am ON");
        } else {
            setBackgroundColor(Color.GRAY);
            setText("I am OFF");
        }
    }
    
    public Switch(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
    public Switch(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }
}

Here we defined the setIsTurnedOn method and called the function changecolor to change the color and text of the switch button according to the prop which we provided in javascript. An onClickListener is also set up for changing the color and text of the button on clicking event.

That’s it!!

Now, try to run the app in the android emulator. You’ll see something like this:

And after clicking on the button:

You can try to change the value of the isTurnedOn prop in the javascript code and see the results for yourself.

In this article, we have created both the Native Modules and Native UI components and used them through the react-native javascript code.

Categories
React Native Web ReactJS

React Native Web Vs React – A Comparison Guide For 2020

Often many of you are wondering isn’t React already existing for many years now and what is the point of the react-native web? Also, some people are thinking are both React native web and React the same thing?

Let’s check this comparison guide for 2020 for React native web and React and find out how “React-native for web” makes it possible to run React native components and APIs on the web using React DOM.

It is as simple as that. So, if you have an app and you want to build a web version of it, you should definitely learn React Native Web.

React Native Web Vs React

React web came before react native and much before react native for web.

Since react used virtual dom concept and there was a code conversion from jsx to html, developers thought of using the same concept for the apps, i.e. Write jsx and convert the code into java and objective c under the hood. And that’s how react native was born.

Also, developers thought of simplifying the code writing process by writing one code instead of two codebases. This way you have to write just one code and let it get converted into html, java, and objective c under the hood. And that’s how React native for web was born.

Is React Obsolete now or can React Native Web And React Together?


Although react native web is a great way to build your website, but I’d say use it only when you have plans to build both web and app versions together, or if you already have an app in react-native and are planning to launch the web version.

But, If you are looking to build only the website, then React is the way to go.

Advantages of React over React Native Web

  • React’s syntax is close to html. In React, we use div, h1, h2, p etc, and it is easier for a frontend engineer with html background to jump in. Whereas in react-native-web, we use <View>, <Text> which is what is used in reactnative, and is different than html way of coding.
  • You can easily fiddle with browser’s inspect element and change the html over there to test your changes in React, as the conversion of React code to the browser is relatively straightforward. Whereas in react native for web, the metro bundler auto-generates the classes, and it looks like the following:  You can’t really change the html directly for trial and error, you need to change the code in your editor itself.
react native web vs react

  • You can easily integrate thirdparty libraries. Most of the third-party libraries have react packages, even if they don’t you can easily integrate the library in the raw html and js form. Whereas with react-native-web integrating third-party libraries may not be that straightforward, although sometimes you can always create mocks.
  • React is more stable and you’d find a lot of documentation about almost everything on the web. Additionally, React has great community support.
  • React native for web is relatively new technology and you won’t find a lot of documentation for it. But it is picking up, so it’s a very good technology to learn.

Advantages of React Native Web over React

  • If you already have a codebase in react-native written, then with minimal changes you can run the same code on to the web. Whereas if you choose react, then you have to start almost from scratch. Although, you can save some time by setting a monorepo and keeping some utils code common between both the app and the web.
  • React native web is great if you want to build app and web versions together as it provides maximum code sharing, whereas with React you have to keep the view files separately.

As the community is driving towards using styledcomponents everywhere, slowly it is going to be quite similar development efforts to use react-native-web and react.


Now, Let’s have a look at the fundamentals of react-native-web:

Fundamentals of the React-Native Web:

Every frontend framework needs to have few things to make it usable.

  • Easy to start
  • Great development experience
  • Navigation
  • Styling
  • Good community support



Easy to Start

Setting up react native for web is quite easy with the expo. Since expo sdk version 33, expo gave the support of react-native web. Check out this detailed article for the react-native-web setup with expo.

Great Development Experience

With the expo kit, you get hot reloading and other great development benefits and experiences. Its been seen that changing styles sometimes get difficult with react-native-web when you are coming from html background and don’t’ have much experience with react-native.

Navigation

React-navigation is one of the most popular navigation library for react-native, and since version 3.0 it has extended the support for react-native for the web as well. Here is a great article if you are interested in integrating react-navigation with react-native-web.

Styling

Styling react-native-web component is exactly the same as styling react-native components. In case, you want to have specific styling for the web, you can always write the conditional styling using Platform.OS === ‘web’ check.

Good Community Support

Since react native web is a recent technology hence it doesn’t have a community as big as react. But you’ll for sure get a lot of help on the web. You can file issues on the official github repo https://github.com/necolas/react-native-web, ask questions over stackoverflow, reach out to us at codersera.com/contact. And If you are looking for a react-native-web developer to build your app and web all in one go, you can try our 7 days risk-free trial services.

Codersera risk free policy

Categories
React Developers React Native Developers React Native Web ReactJS

Running react-native-web using expo in 2020

Since expo sdk version 33, expo supports react-native-web.

In this blog, we’ll see how to set up your react-native-web project using expo.

Installing expo


// install expo-cli
npm i -g expo-cli

// create expo project
expo init

Install expo-cli if you don’t have it installed already, you can use nvm and yarn as well instead of npm.

After running expo init you’ll be presented with a few options to choose the starter kit from.

You can choose any one of those, but for this blog, we’ll use the first one, which is the blank project in javascript. Now, it will prompt you to enter the project name and the slug. Slug is the URL part that’s needed when you try to publish the app on the expo server.

cd into the project directory and run the expo start --web

If you want to quickly jump and see the code, check this GitHub repo [master branch]


cd rn-web
expo start --web

It should launch the webapp in your browser.

expo with react native web

Let’s make some changes in the App.js file and check if hot reloading works.


// App.js
export default function App() {
  return (
    <View style={styles.outer}>
      <Header/>
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app! let me do some change</Text>
      </View>
    </View>
  );
}

You should see the browser reflecting the changes automatically. If you’d like to see my hussle with react-native-web setup check this video.

Adding components to react-native-web

Let’s add a few components to our app now.
Create a Header.js file in components folder


// components/Header.js

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

const {width, height} = Dimensions.get('window');

function Header () {
        return (
            <View  style={styles.header}>
                <Text>I'm header</Text>
            </View>)
}
const styles = StyleSheet.create({
        header: {
               height: height/10,
            alignItems: 'center',
            justifyContent: 'center',
            backgroundColor: 'red',
        },
});
export default Header;

And include Header.js in your App.js file.


// App.js

import React from 'react';
import {Dimensions, StyleSheet, Text, View} from 'react-native';
import Header from './components/Header';
const {width, height} = Dimensions.get('window');

export default function App() {
  return (
    <View style={styles.outer}>
      <Header/>
      <View style={styles.container}>
        <Text>Open up App.js to start working on your app! let me do some change</Text>
      </View>
    </View>
  );
}

const styles = StyleSheet.create({

  outer: {
    flex: 1,

  },
  container: {
    height: height*9/10,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

react-native-web

On the terminal, press i and it will launch the ios simulator or press a and it will launch android emulator, and you should see the app running in the mobile device as well.

react-native-web-expo

If you want to avoid using terminals, Expo also provides you with the browser UI interface which looks like this.

expo in browser

This is the beauty of react-native and react-native-web, you need to write the code once and can run it on multiple platforms. Like react-native-web there are other packages like react-native-windows which lets you run react native apps on the windows phone and PC.

Similarly, react-native-macos let’s your run the app on mac os.

In the next blog, we’ll integrate the navigation library into react-native-web as navigation is an important part of any frontend framework.

Categories
React Developers React Native Developers React Native Web

How to do navigation in React native web in 2020

“React Native for Web” makes it possible to run React Native components and APIs on the web using React DOM.

It is as simple as that!!
So, if you have an app and you want to build a web version of it, or if you are planning to build a website along with an app, you should definitely learn React native web.

Setting up navigation in reactnativeweb is challenging as the navigation system works quite differently in apps vs browser.

In this article, we’ll set up the most popular react-navigation on to react-native-web.

Using React navigation in react native web

React navigation is the most famous library for navigation in reactnative. In this section, we’ll try to integrate react-navigation in reactnativeweb.

Prerequisite

For this setup, we’ll be using expo as the platform on which we’ll be building our reactnative app, which will run on android, ios, and the web.
Make sure you have expo-cli installed already.

To set up your codebase using expo, check this GitHub link [master branch]. Simply clone the branch and do run expo start

If you are looking for a quick code, then you can check this GitHub link [NOTE: the branch is reactnavigationsetup and not master.]

Installation

Run the following command to install reactnavigation along with other needed packages including reactnavigationstack.


expo install react-navigation react-native-gesture-handler react-native-reanimated react-native-screens


npm i react-navigation-stack
npm i @react-navigation/web

Check your package.json files to ensure all of the above packages are installed, make sure reactnavigation is version 4+. If you are wondering, why did we use expo instead of NPM/yarn while installing reactnavigation, then the reason is that expo would look for the correct version of the reactnavigation libraries that’d work with the expo version that’s installed in your project.

If you look into the printed console it uses NPM underneath.

Create a few screens

Now, let’s set up a few screens to test our navigation flow:

  • Profile screen
  • Post screen

// feed screen

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

export default class Feed extends React.Component {

    render() {
        return <View style={styles.container}>
            <Text>This is the feed screen</Text>
           <Button
                    title="Go to Profile"
                    onPress={() => this.props.navigation.navigate('Profile')}
            />


        </View>
    }
}

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

The above is the code for FeedScreen, which is a simple text, and a button. The button when clicked should go directly to the profile screen.


// Profile screen

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

export default class Profile extends React.Component {

    render() {
        return <View style={styles.container}>
            <Text>This is the profile screen</Text>
            <Button
                title="Go to Feed"
                onPress={() => this.props.navigation.navigate('Feed')}
            />

        </View>
    }
}

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

The Profile screen is the same as the Feed screen. Both the screens have a button which takes to the other screen.


Let’s also create stack navigation to connect these two screens together:

// Home.js, just a name of the stack navigation

import {createStackNavigator} from 'react-navigation-stack';
import {createAppContainer} from 'react-navigation';

import Feed from "../screens/Feed";
import Profile from "../screens/Profile";


const Home = createStackNavigator(
    {
        Profile: Profile,
        Feed: Feed,
    },
    {
        navigationOptions: {
            headerTintColor: '#fff',
            headerStyle: {
                backgroundColor: '#000',
            },
        },
    }
);

const container = createAppContainer(Home);

export default container;

Since the object that’s passed to CreateStackNavigator Profile comes first, the Profile screen is the default screen of this stack navigator.

Now, in the App.js file, simply render the Home Navigation.


// App.js

export default function App() {
  return (
    <View style={styles.outer}>
      <Home/>
    </View>
  );
}

Just run the app using command expo start , and it should launch the expo bundler for you.

If you press i to launch the Expo app in the IOS simulator in the terminal, the following screen comes up on display, if everything goes well.

When you click on the Go to Feed button, it should take you to the feed screen.

To run the same setup on to the web, simply press w in your terminal, it will launch the web app in your default browser.

The click functionality also works on the web as well. The top border is for the screen title, you can add it by adding navigationOptions to the feed and profile screen like this.


export default class Feed extends React.Component {
    static navigationOptions = {
        title: "Feed"
    }
...

But there is one problem with the web navigation, the URL doesn’t change when you go from the profile to the feed screen.
In the web navigation, it is extremely important to have the change in page reflecting in the URL as well.

In the app, there is no way a user can directly jump to a screen other than the default screen, but in the browser it is possible, a user can enter a URL.

The good part of reactnavigation is that it supports URL updates when the screen changes. The way navigationOptions is added inside the screen class similarly you can also add title.


export default class Feed extends React.Component {
    static navigationOptions = {
        title: "Feed"
    }

    static path = "feed";

    render() {
...

For the profile screen, you can keep the path as empty static path = "".


When you go to http://localhost:19006/feed, the web app would understand that you want to go to the feed screen and will render that for you. Try going to http://localhost:19006/feed directly, and it should render the feed page for you.

But when you click on the Go to Feed button, the URL won’t change.

There are a few other things that we need to do to make this work:
@react-navigation/web also provide Link module which gets converted into a tag on to the web.

And, this module doesn’t work when you try to run the app. So, we use Platform module provided by reactnative to differentiate between web and app.


// feed screen

import React from 'react';
import {View, Text, StyleSheet, Button, Platform} from 'react-native';
import {Link} from "@react-navigation/web";

const isWeb = Platform.OS === 'web';


export default class Feed extends React.Component {
    static navigationOptions = {
        title: "Feed"
    }

    static path = "feed";

    render() {
        return <View style={styles.container}>
            <Text>This is the feed screen</Text>
            {
                !isWeb ? <Button
                    title="Go to Profile"
                    onPress={() => this.props.navigation.navigate('Profile')}
            />:  <Link routeName="Profile">Go Profile</Link>

            }


        </View>
    }
}

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

Here, we are conditionally rendering the Link and the Button.

You need to do similar changes for the Profile screen as well. Also, in the navigation container, instead of createAppContainer you need to use createBrowserApp for the web.

Here is the code for the navigation:


// Home.js, just a name of the stack navigation

import {createStackNavigator} from 'react-navigation-stack';
import {createAppContainer} from 'react-navigation';
import {createBrowserApp} from '@react-navigation/web';

import Feed from "../screens/Feed";
import Profile from "../screens/Profile";
import {Platform} from "react-native";

const isWeb = Platform.OS === 'web';


const Home = createStackNavigator(
    {
        Profile: Profile,
        Feed: Feed,
    },
    {
        navigationOptions: {
            headerTintColor: '#fff',
            headerStyle: {
                backgroundColor: '#000',
            },
        },
    }
);

const container = isWeb ? createBrowserApp(Home): createAppContainer(Home);

export default container;

Try running the app in the browser, Go to feed button click should change the URL to http://localhost:19006/feed.

Also, the app should be running fine on the simulators as well.

In the following videos, I have done the walkthrough of the reactnavigation setup on react native web.

Categories
Development Frontend Developers React Developers React Native Developers React Native Web ReactJS Top Coder

How To Make React VR Apps

VR web apps can be built with the React VR apps. WebVR is an experimental API enabling the creation and viewing of VR experiences in your browser. This new technology enables you to grant access to virtual reality regardless of the devices at hand.

The only thing you need to make a React VR app is a headset and a compatible browser. If you are just viewing a web VR application then you don’t need even for a headset. React VR is a great framework to build VR websites or apps on JavaScript. It utilizes the same design as React Native and lets you make virtual reality tours and under interfaces with the provided components.

Complete Example

is a headset and a compatible browser. If you are just viewing a web VR application then you don’t need even for a headset. React VR is a great framework to build VR websites or apps on JavaScript. It utilizes the same design as React Native and lets you make virtual reality tours and under interfaces with the provided components.

Technical Requirements


Before getting started with React VR, You required a proper setup for the dependencies that will be used to build and manage a React VR app. These are Node.js and the React VR CLI.

You need to install Node.js, ensure that the latest version is used. If not, do the following:

  • MacOS: Install Node.js using Homebrew
  • Windows: Install it from the nodejs.org
  • Linux: Use sudo apt-get install nodejs command

Then you have to install the React VR CLI using npm:

npm install -g react-vr-cli.

Getting Started


Navigate to the directory where you wish to create a new project and run the react-vr init MyFirstReactVR command.

Change the directory name to something like MyFirstReactVR and run npm start .

Click and try to drag your cursor around. Also, in browsers that support WebVR, you’ll be able to explore this VR environment with a headset in full virtual reality mode.

VR Tour Sample Using React VR


Now let’s make a VR tour with a few scenes and navigations in them. First of all, you need to prepare the architecture. In this example, we will make buttons within each scene for navigations and declare this in the constructor of a React component named index.js.vr:

constructor(props) {
    super(props);
    scenes: [{
        scene_image: 'initial.jpg',
        step: 1,
        navigations: [{
            step: 2,
            translate: [0.73, -0.15, 0.66],
            rotation: [0, 36, 0]
        }]
    }, {
        scene_image: 'step1.jpg',
        step: 2,
        navigations: [{
            step: 3,
            translate: [-0.43, -0.01, 0.9],
            rotation: [0, 140, 0]
        }]
    }, {
        scene_image: 'step2.jpg',
        step: 3,
        navigations: [{
            step: 4,
            translate: [-0.4, 0.05, -0.9],
            rotation: [0, 0, 0]
        }]
    }, {
        scene_image: 'step3.jpg',
        step: 4,
        navigations: [{
            step: 5,
            translate: [-0.55, -0.03, -0.8],
            rotation: [0, 32, 0]
        }]
    }, {
        scene_image: 'step4.jpg',
        step: 5,
        navigations: [{
            step: 1,
            translate: [0.2, -0.03, -1],
            rotation: [0, 20, 0]
        }]
    }]
}

Also, declare current_scene in the state in the constructor:

constructor(props) {
        this.state = {
            ...
            current_scene: {}
                ...
        }

For rendering, change the render() method, as seen below:

render() {
    return ( < View >
        < Pano source = {
            asset(this.state.current_scene['scene_image'])
        }
        style = {
            {
                transform: [{
                    translate: [0, 0, 0]
                }]
            }
        }
        /> {
            this.state.current_scene['navigations'].map(function(item, i) {
                return <Mesh key = {
                    i
                }
                style = {
                        {
                            layoutOrigin: [0.5, 0.5],
                            transform: [{
                                translate: item['translate']
                            }, {
                                rotateX: item['rotation'][0]
                            }, {
                                rotateY: item['rotation'][1]
                            }, {
                                rotateZ: item['rotation'][2]
                            }]
                        }
                    } >
                    < VrButton
                style = {
                        {
                            width: 0.15,
                            height: 0.15,
                            borderRadius: 50,
                            backgroundColor: 'blue'
                        }
                    } >
                    < /VrButton> < /Mesh>
            })
        } < /View>
    )
}

The last step to make this work is to set the current_scene state to the first element of the scenes array componentWillMount function:

componentWillMount() {
    this.setState({
        current_scene: this.state.scenes[0]
    });
}

The result should be like this on screen:

Now add a simple animation for the button and implement the logic to navigate between scenes. First of all, for navigation, you need to subscribe to the onInput event for our Mesh element, bind this function to this in constructor, and implement it:

...
constructor(props) {
    ...
    this.onNavigationClick = this.onNavigationClick.bind(this);
    ...
}
...
onNavigationClick(item, e) {
        if (e.nativeEvent.inputEvent.eventType === "mousedown" && e.nativeEvent.inputEvent.button === 0) {
            var new_scene = this.state.scenes.find(i => i['step'] === item.step);
            this.setState({
                current_scene: new_scene
            });
        }
    }
    ...
render() {
    var that = this;
    ... < Mesh key = {
            i
        }
        ...
    onInput = {
            e => that.onNavigationClick(item, e)
        }
        .... >
        ...
}

Then added a simple animation try it out. For this, you have added one more button inside the existing one in the render method and changed the size of it. Use native JS requestAnimationFrame function:

const DEFAULT_ANIMATION_BUTTON_RADIUS = 50;
const DEFAULT_ANIMATION_BUTTON_SIZE = 0.05;
constructor(props) {
        ...
        this.state = {
                ...
                animationWidth: DEFAULT_ANIMATION_BUTTON_SIZE,
                    animationRadius: DEFAULT_ANIMATION_BUTTON_RADIUS
                    ...
            }
            ...
        this.animatePointer = this.animatePointer.bind(this);
    }
    ...
componentWillUnmount() {
    if (this.frameHandle) {
        cancelAnimationFrame(this.frameHandle);
        this.frameHandle = null;
    }
}
componentDidMount() {
    this.animatePointer();
}
animatePointer() {
        var delta = this.state.animationWidth + 0.002;
        var radius = this.state.animationRadius + 10;
        if (delta >= 0.13) {
            delta = DEFAULT_ANIMATION_BUTTON_SIZE;
            radius = DEFAULT_ANIMATION_BUTTON_RADIUS;
        }
        this.setState({
            animationWidth: delta,
            animationRadius: radius
        })
        this.frameHandle = requestAnimationFrame(this.animatePointer);
    }
    ...
render() {
    ... < VrButton
    style = {
            {
                width: 0.15,
                height: 0.15,
                borderRadius: 50,
                justifyContent: 'center',
                alignItems: 'center',
                borderStyle: 'solid',
                borderColor: '#FFFFFF80',
                borderWidth: 0.01
            }
        } >
        < VrButton
    style = {
            {
                width: that.state.animationWidth,
                height: that.state.animationWidth,
                borderRadius: that.state.animationRadius,
                backgroundColor: '#FFFFFFD9'
            }
        } >
        < /VrButton> < /VrButton>
        ...
}

Now let’s implement manipulations with the animated button and its rotation. It will rotate the button on an X-Y-Z axis. To do so, you need to subscribe to the onInput event for the Pano component and change the rotation via arrow-up, arrow-right, and arrow-down buttons.

The last thing is to implement messaging of the VR thread and Main thread to exchange data. Below is the subscription code on receiving messages and posting a message when a scene changes or an image starts/ends loading.

componentWillMount() {
      window.addEventListener('message', this.onMainWindowMessage);
      ...
  }
  onMainWindowMessage(e) {
      switch (e.data.type) {
          case 'newCoordinates':
              var scene_navigation = this.state.current_scene.navigations[0];
              this.state.current_scene.navigations[0]['translate'] = [e.data.coordinates.x, e.data.coordinates.y, e.data.coordinates.z]
              this.forceUpdate();
              break;
          default:
              return;
      }
  }
  onNavigationClick(item, e) {
      ...
      postMessage({
          type: "sceneChanged"
      })
      this.state.animationWidth = DEFAULT_ANIMATION_BUTTON_SIZE;
      this.state.animationRadius = DEFAULT_ANIMATION_BUTTON_RADIUS;
      this.animatePointer();
      ...
  }
  sceneOnLoad() {
      postMessage({
          type: "sceneLoadStart"
      })
  }
  sceneOnLoadEnd() {
      postMessage({
          type: "sceneLoadEnd"
      })
  }
  render() {
      ... < Pano...
      onLoad = {
          this.sceneOnLoad
      }
      onLoadEnd = {
              this.sceneOnLoadEnd
          }
          ... / >
  }

In client.js, implement a zoom with the mouse wheel and a position change with a double-click. you need to store the VR instance and VRcamera instance to implement the logic above.

function init(bundle, parent, options) {
    const vr = new VRInstance(bundle, 'TMExample', parent, {
        // Add custom options here
        ...options,
    });
    vr.render = function() {
        // Any custom behavior you want to perform on each frame goes here
    };
    // Begin the animation loop
    vr.start();
    window.playerCamera = vr.player._camera;
    window.vr = vr;
    return vr;

Then subscribe to ondblclick and onmousewheel and implement the zoom and change position logic.

function onRendererDoubleClick() {
      var x = 2 * (event.x / window.innerWidth) - 1;
      var y = 1 - 2 * (event.y / window.innerHeight);
      var coordinates = get3DPoint(window.playerCamera, x, y);
      vr.rootView.context.worker.postMessage({
          type: "newCoordinates",
          coordinates: coordinates
      });
  }
  function onRendererMouseWheel() {
      if (event.deltaY > 0) {
          if (window.playerCamera.zoom > 1) {
              window.playerCamera.zoom -= 0.1;
              window.playerCamera.updateProjectionMatrix();
          }
      } else {
          if (window.playerCamera.zoom < 3) {
              window.playerCamera.zoom += 0.1;
              window.playerCamera.updateProjectionMatrix();
          }
      }
  }

get3DPoint is your custom function to transform screen coordinates to world coordinates using Three.js, implemented in cameraHelper.js.

import * as THREE from 'three';
export function get3DPoint(camera, x, y) {
    var mousePosition = new THREE.Vector3(x, y, 0.5);
    mousePosition.unproject(camera);
    var dir = mousePosition.sub(camera.position).normalize();
    return dir;
}

Sometimes, loading scene images takes time. thus, you have implemented the loader to show this process. In index.html, add a loader and CSS based on this w3cschool example.

<style>
    body { margin: 0; }
    #loader {
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 1;
    width: 150px;
    height: 150px;
    margin: -75px 0 0 -75px;
    border: 16px solid #f3f3f3;
    border-radius: 50%;
    border-top: 16px solid #3498db;
    width: 120px;
    height: 120px;
    -webkit-animation: spin 2s linear infinite;
    animation: spin 2s linear infinite;
    }
    @-webkit-keyframes spin {
    0% { -webkit-transform: rotate(0deg); }
    100% { -webkit-transform: rotate(360deg); }
    }
    @keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
    }
    .animate-bottom {
    position: relative;
    -webkit-animation-name: animatebottom;
    -webkit-animation-duration: 1s;
    animation-name: animatebottom;
    animation-duration: 1s
    }
    @-webkit-keyframes animatebottom {
    from { bottom:-100px; opacity:0 }
    to { bottom:0px; opacity:1 }
    }
    @keyframes animatebottom {
    from{ bottom:-100px; opacity:0 }
    to{ bottom:0; opacity:1 }
    }
    #myDiv {
    display: none;
    text-align: center;
    }
</style>
<body>
    <div id='content' style="width:100%; height:100%">
        <div id="loader"></div>
    </div>
    <script src="./client.bundle?platform=vr"></script>
    <script>
        ReactVR.init('../index.vr.bundle?platform=vr&dev=true', document.getElementById('content'));
    </script>
</body>

And don’t forget message in client.js from the VR thread to enable/disable animation:

function init(bundle, parent, options) {
    ...
    vr.rootView.context.worker.addEventListener('message', onVRMessage);
    ...
  }
  function onVRMessage(e) {
    switch (e.data.type) {
      case 'sceneChanged':
      if (window.playerCamera.zoom != 1) {
        window.playerCamera.zoom = 1;
        window.playerCamera.updateProjectionMatrix();
      }
      break;
      case 'sceneLoadStart':
        document.getElementById('loader').style.display = 'block';
      break;
      case 'sceneLoadEnd':
        document.getElementById('loader').style.display = 'none';
      break;
      default:
      return;
    }
  }

Check your index.html or client.js.

Get The Complete Github Code Here

Categories
Development Javascript React Native Web Top Coder

Should I Still Be a Programmer After 40?

Developers are equipped with multiple skills ranging from designing a new product to write complex code. And the age is just a number if you truly love your profession. There are many developers who think that what they do when they turn above 40.

According to Mr. Josan senior developer, here at Codersera says- “developing software is my passion which makes me younger and self-motivated after 45.”

Mr. Josan is one of our senior developer who says that “age is just a number”, if you have the potential to learn new technologies and continuously upgrade yourself with new trends. He is 45 years old and works with young people and manage his team perfectly. He works so energetically as well as handles the projects professionally without any ” “. With the experience of over 15 years as a software developer, he learned every new technology which came in the market and always updated his team with it.

“Once a programmer always a programmer.”


There is no age limit to be a programmer, it just depends on your skills and abilities to coding and innovate something new. As we know experience is also important. In every company, most of the employees are experienced and the companies also prefer experienced people in their team.

Why companies hire experienced developers?

  • More experience.
  • Easily handle the situations.
  • More familiar with coding languages.
  • Capable of managing a complex project.

Self-motivation is more important to continue your journey as a developer. There are many people who think that developers career is ended after 40, which is a hoax but they have more experienced and skilled to work. Even after 40, some people start their career as a developer and work as remote developers and freelancers, which give them the opportunity to follow their passion.

No one decides your career age for you or when will you retired from work. Not even the programming languages set their limits of learning. All you need is a chair, laptop, and working internet connection and you good to go.


How to enhance yourself with new technologies?


There are many developers who stop working after the age of 40. here we mention some point which can motivate you, here are some points that increase your interest and motivate you to continue your developing skills.

And after introspect and discussion with Mr. Josan, here I come up with very interesting techniques of motivation.

  • Never stop yourself from creating something new:

Being a developer, the first thing that you should keep in your mind is you never be afraid to face challenges. You know every line of code is written to create something new. The product you create is something that gives you the satisfaction of your hard work. And startups like Uber, Netflix, and Airbnb are some examples of how you can create something amazing with lines of code.

  • Never stop yourself from learning new technologies:

Python and r are beginner-friendly and their syntaxs are like simple English, and there are many online sources (paid and free) through which you can learn languages on your own.

Programming languages are upgraded fequently which make it learn with fun. Like React, React Native and then React Native web- these framework uses javascript as their base which makes them easier to learn. programming languages are easy to learn after you master any 1 programming language, for example: if you learn C++ you can easily learn Java, Python as the syntax changes but the logics remain the same.

Some sources where you learn programming languages.

  1. khan academy (Free)
  2. treehouse (paid)
  3. udemy (Paid)
  4. codecademy (Freemium)
  5. The New Boston (Free)
  • Never stop believing yourself:

Age never defines your abilities to learn, unless you believe in you. You are the developers who builds applications & software from the betterment of the future. don’t forget every new programmer was once a fresher and it’s not their age that got them where they are right now, it’s their passion towards creating something new using their coding skills. and once you start programming your passion along with your experience will take you to new heights or the programmer you wants to become.

  • Always respect your work:

Irrespective of your work profile you should always take pride the work you do. The programmers are proudly known by their intelligence and technical aptitude. For any tech organization, the developer’s opinions are very important especially when they are the serious or experienced one. Respect towards your work is a great motivator form you to even work after 40 or 50 years of age.

Job as a developer can be classified as a never-ending job if you never stop yourself to learning new skills and practice it. If you want to grow and last longer in your field of interest, the all you need to do is learn to adopt the latest technologies to increase your knowledge.

codersera


As shown in the graph, there are the maximum number of people are of age group 20-24 with 80% and less in >60 age group. It is because there are more developers of younger age and they have great and huge oceans of new ideas. So, the age group of people 20-24 has the highest percentage because at this age people are more energetic and familiar with new technologies and easily get things done.

The reasons- why companies prefer freshers?

  • New ideas
  • More productive work
  • Fast working abilities
  • Aware and use to with new technologies easily
  • Good knowledge of trends
  • Easily available


Freshers have considered more productive but old employees had huge experience to manage or handle any project alone. The best thing that happens in between them is new ideas and old experience build an amazing team.

As well as working with experienced persons, the freshers excellent knowledge and learn from their mistakes.

Categories
Business Development React Native Web Resume Startup Top Coder

Ubuntu Vs Mac OS


An operating system (OS) is system software that manages computer hardware, software resources, and provides common services for computer programs. (source: Wiki).
All major platforms (hardware and software) require an operating system. In general, OS is a software that allows users to run other application programmes in a computing device. Ubuntu and Mac are the second most common desktop OS after windows.

History Of Ubuntu


Linux has come with a lot of distros and its popular distribution is Ubuntu. Linux was already established in 2004, but it was not open source for every user. Hence Mark Shuttleworth decided to make a team of developers from the one of established project Debian and create an easy to use Linux desktop: Ubuntu. Ubuntu has free software available for all and funded through a portfolio of services provided by canonical.


Linux is a popular open-source operating system which is also referred to as Linux kernel. Linux is an open-source platform where user can download it and modify its source code. It is the most-used OS for desktop and server application. It provides all necessary components (tools, service and programmes) for a fully operating system.


They give special privilege to some highly qualified developers for being part of their free software foundation as Linux/GNU to build a better community. Many companies in the market make various Linux OS and core kernel with all components but Linux kernel is developed and maintained by Linux foundation.

Releases:


Ubuntu released on 20 October 2004 and it’s latest released version is Ubuntu 19.4 (18 April 2019).

Linux kernel was first released on September 17, 1991, by Linus Torvalds. It was originally developed for Intel x86 computers but later, ported to other platforms as well. Having dominancy in android OS smartphone, Linux has highly installed in the general-purpose operating system.


Linux is the foundation of many opearting systems like Android, Arch Linux, Debian Linux, Gentoo Linux, Ubuntu, Mandriva Linux, Pc, red hut Linux, Sabayon Linux, Slackware, Suse Linux.

History Of Mac OS


Mac OS is an operating system of Apple computer Mactonish series, (computers and workstations) having a graphical user interface which is only developed and maintained by Apple engineers themselves. Apple developed the whole system including Kernal, desktop environment and pre-installed software. Mac OS is the second major series of Mantonish operating system.
Apart from all specifications, it looks better than other systems as well.(personal preference)

Version History:


Apple developed its first operating system as Classic Mac OS with the original Mactonish system software in 1984. The current Mac operating system is Mac OS, the original name was Mac OS X. Later on, Apple purchased Nextstep and brought a new Architecture based Unix System to improve its design.
The latest version of OS X comes with desktop interface with some 3D appearances characteristics. OS X has a Modular design to make easier to add new features into the operating system in future updates. It runs Unix application as well as older Mac applications.

The first desktop version Mac OS launched on March 24, 2001. Since then, Apple has been constantly updating new features and technologies in their new updates.
Apple has been Releasing new systems every year since 2011.

  • Mac OS X LION – version 10.7 released in 2011
  • OS X Mountain Lion – version 10.8 released in 2012
  • OS X Mavericks – version 10.9 released in 2013
  • OS X Yosemite – version 10-10 released in 2014
  • OS X EI Captain – version 10.11 released in 2015
  • Mac OS Sierra – version 10.12 released in 2016
  • Mac OS High Sierra – version 10.13 released in 2017
  • Mac OS Mojave – version 10.14 released in 2018

Ubuntu Vs. Mac: Which System To Choose


Customization:


If we talk about Ubuntu, it is not an OS. It is a completely a kernel which was developed and maintained by Linux foundation. It is an open-source kernel which means individual developers can use it in their personal projects and modify its source code.

On the other hand, Mac OS is an operating system of Apple’s Mactonish series which don’t allow us for exclusively controls and you can’t even able to look Mac OS source code.
Apple more focuses on Mac’s UI to make it more enjoyable.

Performance:


Linux comes with a various desktop environment which totally depends on users need and demand. In spite of heavy resource demand system and lightweight distros, Linux gives you solid system stability and high performance across the device.

Apple is quite stable to perform regular tasks. It’s OS has a well-integrated system process that makes it strongly stable and high performance.

Hardware:


Ubuntu is one of the widely used OS in the market. All the major vendors provide its hardware compatible driver. You can install it on any system, no matter how powerful or older system you have.

Mac shines in this sector because Apple uses its OS only in Apple-made hardware. Thus it provides stable, and well-integrated hardware and software combined system with the highest performance.
It only runs on Apple computers, thus we face less hardware and software crashes.

Security And Privacy:


Ubuntu does not track any digital footprints and it’s very hard to create any backdoor in a Linux kernel system. Thus it became very popular among IT professionals because security and privacy is the key factor of Linux.

A lot of people praise Mac for being a secure platform. Although they track their users for giving them a product or service. Mac OS is nicely organised walled garden by Apple for its users.

Malware And Antivirus:


Canonical claims that you don’t need to install anti-virus in Ubuntu because of viruses which can affect Ubuntu are very rare.
Although being an open-source Linux still has very few bugs. Ubuntu provides a robust system to prevent malware and online threats. It has also a large community to help you in a security breach at system anytime, anywhere.
For keeping system files and user’s common data secure, Ubuntu does not provide administrative and root access.

Mac gets almost no viruses. Mac provides stable security patches, as soon as any bug found.,
Mac is a better choice if you are conscious about your privacy as it is very difficult to hack. Hence Mac is a secure option.

Install, Update And Upgrade:


Ubuntu is very easy to install. It comes with an interface, known as unity.
you can easily visit their website and install Ubuntu by yourself in just a few clicks.

Mac system has already a pre-installed app store which makes very easy and effortless way to get required updates. A non-techy guy can also update the system and software in Mac. Apple is the only vendor who provides all system updates.

Gaming:


Ubuntu supports a steam platform where we can play all games online and offline both. It makes more accessible to play games via Play on Linux or wine environment. But still, there is room for improvement as many game developers don’t make games for ubuntu. That is major drawback if you are planning to use ubuntu for gaming.

Mac is well developed for the highest gaming performance. It gives you a prebuilt system for installing all the latest and trending games.

Price:


Price is one of the key factors for choosing an operating system. When we talk about Ubuntu price, it is completely free. whereas for other operating systems, you have to pay around $100 – $150.

You can’t buy a Mac OS. It only comes with Apple computers and they quite are expensive for some.

Users:


If you are looking for a system with an open-source environment so you should go with Ubuntu because it comes free with a lot of open-source software.
If watching movies, writing documents, creating a spreadsheet and other stuff is only your purpose, Linux would be a great a choice for you.

Mac is suitable for high-end media or graphics. LIke web designing, UI and UX design, product design, sound editing and image editing.
Mac is best for video editing and music production as Final cut pro and logic pro X are a better optimized in Mac.
developers also prefer Mac to work on because of its high performance.

Categories
Angular Frontend Developers Javascript React Developers React Native Developers React Native Web Top Coder

An Angular 5 Tutorial: Step 1 – Guide To Your First Angular 5 App

Let’s get started with your Angular 5 tutorial. First, let me introduce you to Angular 5. Angular 5 is a new version of the AngularJS framework. It is developed by Google. It comes with various improvements like optimized build and faster compile times. Angular 5 also comes with a complete rewrite.

If you want to learn Angular 5 this Angular 5 tutorial is for you. Here we are going to build a notes app from scratch.

An Angular 5 Tutorial: Step By Step Guide To Your  First Angular 5 App


There are two versions of frameworks:-

-AngularJS(Version 1)
-Angular(Version 2+)

There is a huge difference between these two is AngularJS is a javascript framework but version 2 Angular is not a javascript framework.

Conflict b/w use or not to use Angular 5:-


Some developers prefer to use React and build their components without additional codes. But that may be a problem, too.

On the other hand, some developers choose Angular as it is a fully integrated framework. Angular allows you to quickly start working on your project without giving thought about which library to select and also how to deal with everyday problems. That is why here we are building our first Angular 5 App.

TypeScript


TypeScript is easy to learn if you have a good knowledge of JavaScript. Most modern editors are quite effective in helping with that. Nowadays the most preferable options are VSCode and any of the JetBrains IntelliJ family-like Webstorm and RubyMine.

It’s good to use a smarter editor than vim. As TypeScript is strongly typed, it will give you an extra hands-up on any mistakes in the code. One more thing is that Angular CLI with its Webpack takes care of compiling TypeScript to JavaScript. So you shouldn’t let the IDE compile it for you.

Angular CLI


Angular has its own CLI (command line interface), which will do most of the routines for you. You have to install it first to start using Angular. It requires Node 6.9.0 or higher as well as NPM 3 or Higher. You need to install both for that find up-to-date documentation for installation. Once they both install, you can install Angular CLI by running the following.

npm install -g @angular/cli

Once you successfully install Angular CLI, you can generate a new project by running the ng new command.

ng new getting-started-ng5
  create getting-started-ng5/README.md (1033 bytes)
  create getting-started-ng5/.angular-cli.json (1254 bytes)
  create getting-started-ng5/.editorconfig (245 bytes)
  create getting-started-ng5/.gitignore (516 bytes)
  create getting-started-ng5/src/assets/.gitkeep (0 bytes)
  create getting-started-ng5/src/environments/environment.prod.ts (51 bytes)
  create getting-started-ng5/src/environments/environment.ts (387 bytes)
  create getting-started-ng5/src/favicon.ico (5430 bytes)
  create getting-started-ng5/src/index.html (304 bytes)
  create getting-started-ng5/src/main.ts (370 bytes)
  create getting-started-ng5/src/polyfills.ts (2405 bytes)
  create getting-started-ng5/src/styles.css (80 bytes)
  create getting-started-ng5/src/test.ts (1085 bytes)
  create getting-started-ng5/src/tsconfig.app.json (211 bytes)
  create getting-started-ng5/src/tsconfig.spec.json (304 bytes)
  create getting-started-ng5/src/typings.d.ts (104 bytes)
  create getting-started-ng5/e2e/app.e2e-spec.ts (301 bytes)
  create getting-started-ng5/e2e/app.po.ts (208 bytes)
  create getting-started-ng5/e2e/tsconfig.e2e.json (235 bytes)
  create getting-started-ng5/karma.conf.js (923 bytes)
  create getting-started-ng5/package.json (1324 bytes)
  create getting-started-ng5/protractor.conf.js (722 bytes)
  create getting-started-ng5/tsconfig.json (363 bytes)
  create getting-started-ng5/tslint.json (3040 bytes)
  create getting-started-ng5/src/app/app.module.ts (316 bytes)
  create getting-started-ng5/src/app/app.component.css (0 bytes)
  create getting-started-ng5/src/app/app.component.html (1141 bytes)
  create getting-started-ng5/src/app/app.component.spec.ts (986 bytes)
  create getting-started-ng5/src/app/app.component.ts (207 bytes)
Installing packages for tooling via yarn.
yarn install v1.3.2
info No lockfile found.
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
warning "@angular/cli > @schematics/angular@0.1.10" has incorrect peer dependency "@angular-devkit/schematics@0.0.40".
warning "@angular/cli > @angular-devkit/schematics > @schematics/schematics@0.0.10" has incorrect peer dependency "@angular-devkit/schematics@0.0.40".
[4/4] 📃  Building fresh packages...
success Saved lockfile.
✨  Done in 44.12s.
Installed packages for tooling via yarn.
Successfully initialized git.
Project 'getting-started-ng5' successfully created.

When it’s done, you can ask for your fresh application to start by running ng serve out of its directory:

ng serve
** NG Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ **
Date: 2017-12-13T17:48:30.322Z
Hash: d147075480d038711dea
Time: 7425ms
chunk {inline} inline.bundle.js (inline) 5.79 kB [entry] [rendered]
chunk {main} main.bundle.js (main) 20.8 kB [initial] [rendered]
chunk {polyfills} polyfills.bundle.js (polyfills) 554 kB [initial] [rendered]
chunk {styles} styles.bundle.js (styles) 34.1 kB [initial] [rendered]
chunk {vendor} vendor.bundle.js (vendor) 7.14 MB [initial] [rendered]
webpack: Compiled successfully.


When you navigate your browser to that link, It will be displayed as pictured here:

Let’s get started with Angular 5 Tutorial


Now let’s see what is actually happening here. Angular CLI runs webpack dev server, which renders your app on the next free port because of this you can run multiple apps on the same machine with live reload. It also watches for every change in the project source and recompiles all changes. After that, it asks the browser to reload the open page. So we are already working in a development environment without writing a line of configuration by using Angular CLI. But it’s just a start here…

App composition in angular


You have your empty app running. Now let’s talk about app composition in Angular. If you have basic knowledge of AngularJS you know there were controllers, directives, and components that were somehow like directives but simpler, to allow you to upgrade to Angular 2.

Those who don’t have that wonderful experience of having to choose between them and also figure out what goes where. But you do not need to worry. Nowadays it’s mostly just a component. In the Angular world component is the most basic building block.

Let’s look at the code that was generated for you by Angular CLI.

First, here’s index.html :

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>GettingStartedNg5</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
</head>
<body>
  <app-root></app-root>
</body>
</html>



It looks like the kind of markup. But there’s a special tag, app-root. How does Angular make this work, and how can we know what’s happening inside it?

Let’s open the src/app directory and see what’s there. You can see ng new output from earlier here or open it in your chosen IDE. You will see app.component.ts there were the next bit( this may vary depending on how recent your version of Angular is):


import { Component } from '@angular/core';
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app';
} 

@components(—) here looks like a function call. What is it? there is a TypeScript decorator we will discuss it later. For now let’s concentrate on what it’s doing, with passed parameters like selector being used to generate your component declaration. It just goes a lot of boilerplate work for you as well as giving back your component declaration in its working form. You don’t have to implement additional code to support any of the decorator’s params. It’s all handled by the decorator. Generally, it is called the Factory method.

You already saw app-root in your index.html. Here’s how Angular knows how to find the component corresponding to your tag. Obviously, templateUrl and styleUrls define where Angular should take your markup and CSS from. there are a lot more params for the component decorator. We are also going to use some of them in our new app.

Let’s look at the component’s markup:

<!--The content below is only a placeholder and can be replaced.-->
<div style="text-align:center">
  <h1>
    Welcome to {{ title }}!
  </h1>
  <img width="300" alt="Angular Logo" src="data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyNTAgMjUwIj4KICAgIDxwYXRoIGZpbGw9IiNERDAwMzEiIGQ9Ik0xMjUgMzBMMzEuOSA2My4ybDE0LjIgMTIzLjFMMTI1IDIzMGw3OC45LTQzLjcgMTQuMi0xMjMuMXoiIC8+CiAgICA8cGF0aCBmaWxsPSIjQzMwMDJGIiBkPSJNMTI1IDMwdjIyLjItLjFWMjMwbDc4LjktNDMuNyAxNC4yLTEyMy4xTDEyNSAzMHoiIC8+CiAgICA8cGF0aCAgZmlsbD0iI0ZGRkZGRiIgZD0iTTEyNSA1Mi4xTDY2LjggMTgyLjZoMjEuN2wxMS43LTI5LjJoNDkuNGwxMS43IDI5LjJIMTgzTDEyNSA1Mi4xem0xNyA4My4zaC0zNGwxNy00MC45IDE3IDQwLjl6IiAvPgogIDwvc3ZnPg==">
</div>
<h2>Here are some links to help you start: </h2>
<ul>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://angular.io/tutorial">Tour of Heroes</a></h2>
  </li>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://github.com/angular/angular-cli/wiki">CLI Documentation</a></h2>
  </li>
  <li>
    <h2><a target="_blank" rel="noopener" href="https://blog.angular.io/">Angular blog</a></h2>
  </li>
</ul>


So, aside from embedding the Angular Logo as an SVG, which is pretty neat, this seems like typical everyday markup as well. Aside from one thing ( Welcome to {{ title }} !), If you look at your component code again, you will see title=’app’;. So, if you already have some practice in template languages or have worked with AngularJS, it’s pretty obvious what’s happening here. It is called Angular Interpolation by which the expression inside the double curly braces is being pulled from your component( you can think of {{ title }} as a simplified form of {{ this.title }} ) and also displayed on your markup.

Now you have seen all the parts of your auto-generated Angular app that actually take place in the page displayed in your browser. Let’s recap how it actually works- Angular CLI runs Webpack, which is compiling your Angular app into Javascripts bundles and injecting them into your index.html. If you take a look at the actual code in your browser using the inspect feature, you see something like this:


Every time you change your code, Angular CLI will recompile, re-inject if needed, and also ask your browser to reload the page if it’s open. Angular does it quite quickly, so in most cases, while you are switching your windows from the IDE to the browser, it will all be reloaded for you.

So let’s start moving towards your goal and, for a start, let’s switch your project from CSS to Sass and open your .angular-cli.json and edit styles and styleExt properties thusly.

"styles": [
  "styles.scss"
],
[...]
"defaults": {
  "styleExt": "scss",
  "component": {}
}


You also need to add Sass library to our project and rename styles.css to styles.scss. So to add Sass you need to use yarn :

yarn add sass 
yarn add v1.3.2
[1/4] 🔍  Resolving packages...
[2/4] 🚚  Fetching packages...
[3/4] 🔗  Linking dependencies...
[...]
[4/4] 📃  Building fresh packages...
success Saved lockfile.
success Saved 1 new dependency.
└─ sass@1.0.0-beta.4
✨  Done in 12.06s.
yarn add node-sass@4.7.2 --dev
✨  Done in 5.78s.


If you also want to use Twitter Bootstrap on your project so you also need to runyarn add bootstrap@v4.0.0-beta.2 and edit your styles.scss to include this:

/* You can add global styles to this file, and also import other style files */
@import "../node_modules/bootstrap/scss/bootstrap";
body {
  padding-top: 5rem;
}


you need to edit index.html to make your page responsive by changing the meta for your markup to this:

<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">


And now you can replace app.componant.html with this:

<!-- Fixed navbar -->
<nav>
  <a href="#">Angular Notes</a>
</nav>
<div>
  <div style="text-align:center">
    <h1>
      Welcome to {{title}}!
    </h1>
  </div>
</div>


now, if you open your browser, you see the following:


And that’s it for the boilerplate. Let’s move on to creating your own components.

First Components


Let’s start by generating your first component, representing the card itself. For that, use Angular CLI by running the following command:

ng generate component Card
  create src/app/card/card.component.scss (0 bytes)
  create src/app/card/card.component.html (23 bytes)
  create src/app/card/card.component.spec.ts (614 bytes)
  create src/app/card/card.component.ts (262 bytes)
  update src/app/app.module.ts (390 bytes)


But if you look into src/app/card/card.component.ts , you can see they are almost the same code, as you have in your AppComponent, with one small difference:

[...]
@Component({
  selector: 'app-card',
[...]
export class CardComponent implements OnInit {
  constructor() { }
  ngOnInit() {
  }
}



At this point, that it’s considered good practice to preface your component selectors with a common prefix, and by default, it’s app- You can change it to the prefix of your preference by editing the prefix property in .angular-cli.json ,so it’s preferable to do so before using ng generate for the first time.

So, you have a constructor for your component as well as a ngOnInit function for it. On a basic level, think about these methods like this: A constructor is being called right after the creation of the component, long before data to be passed to it is ready and populated, while ngOnInit only runs after the first cycle of changes to the data, so you have access to your component inputs. Just remember that it is preferable to use the constructor for constants, like things that are actually being hard-coded into your component, as well as ngOnInit for everything that depends on external data.

Let’s populate your CardComponent implementation. To start with, let’s just add some markup to it. Default contents for markup are something like this:


<p>
  card works!
</p>


Replace it with code so it will behave like a card:

<div>
  <div>
    <p>Text</p>
  </div>
</div>


Now is a good time to display the card component, but this raises additional questions: Who will be responsible for displaying the cards? AppComponent? But AppComponent will be loaded before anything else in the app, so you have to consider it to be tidy and small. you’d better create one more component to take care of storing a list of cards and displaying it on your page.

As described component’s responsibilities, it is clear that this is supposed to be a Card List Component. Let’s ask Angular CLI to generate it for you:

ng generate component CardList
  create src/app/card-list/card-list.component.scss (0 bytes)
  create src/app/card-list/card-list.component.html (28 bytes)
  create src/app/card-list/card-list.component.spec.ts (643 bytes)
  create src/app/card-list/card-list.component.ts (281 bytes)
  update src/app/app.module.ts (483 bytes)

Before we start implementing it, Angular CLI tells you that it updated app.module.ts for you, correct it:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { CardComponent } from './card/card.component';
import { CardListComponent } from './card-list/card-list.component';
@NgModule({
  declarations: [
    AppComponent,
    CardComponent,
    CardListComponent,
  ],
  imports: [
    BrowserModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


Obviously, BrowserModule and NgModule are internal Angular modules. AppComponent was here before you started to generate any code, so your new components actually populated the modules in two places. First, they are imported from their definition files and then they are included in the declaration array of your NgModule Decorator. If you are creating a new component from scratch and forget to add a new module to NgModule but try to add it to your markup, your app won’t work with the next error in the JS console.

Uncaught Error: Template parse errors:
'app-card-list' is not a known element:
1. If 'app-card-list' is an Angular component, then verify that it is part of this module.
2. If 'app-card-list' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("


So check your console if your app is not working for no apparent reason.

Let’s populate your card list component markup ( src/app/card-list/card-list.component.html )

<div>
  <div>
    <app-card></app-card>
    <app-card></app-card>
    <app-card></app-card>
  </div>
</div>


If you open it in your browser, you will see something like this :


Currently displaying cards out of the hard-coded markup. Let’s bring your code one step closer to a real case scenario by moving a hard-coded array of cards into your application:

export class AppComponent {
  public cards: Array<any> = [
    {text: 'Card 1'},
    {text: 'Card 2'},
    {text: 'Card 3'},
    {text: 'Card 4'},
    {text: 'Card 5'},
    {text: 'Card 6'},
    {text: 'Card 7'},
    {text: 'Card 8'},
    {text: 'Card 9'},
    {text: 'Card 10'},
  ];
}


You have your initial list, but still, you need to pass it to the component and render it there. for that, you need to create your first input. Let’s add it to your CardList component:

import {Component, Input, OnInit} from '@angular/core';
[...]
export class CardListComponent implements OnInit {
  @Input() cards: Array<any>;
[...]



Imported Input from the Angular code and used it as a decorator for class-level variables cards with type Array of objects of any kind. Ideally, you should not use any but should use strict typing so that you can define something like an interface card, which will contain all the properties of your card.

Now you have your card array in your CardList. Let’s take a look at the new code in your card list component.


<app-card *ngFor="let card of cards"></app-card>



An attribute name that starts from an asterisk. What does it mean? It’s a default convention for naming Angular structural directives. Structure directives control the structure of your template. The asterisks here is actually “syntax sugar,“. But for your current example, its enough to understand what will happen when you add it to your component. So ngFor a repeater directive and it will repeat your app card for every element in the array of cards. If you look at the browser, you see this next:



Something is not right; you have your array of cards, but you are getting an empty page.

You define your array of cards on the AppComponent level, But you haven’t passed it to CardList input. Let’s edit your AppComponent template to do that.


<app-card-list [cards]="cards"></app-card-list>



This syntax – The attributes in the square brackets – tells angular that you would like to one-way bind your component variable cards to your Card List component [cards] input. As soon as you do that, you get this:


Of course, you want to display the actual contents of your card array, and for that, you need to pass the card object to the card component as well. Let’s extend your Card List component:

<app-card *ngFor="let card of cards" [card]="card"></app-card>



And if you look in the browser right now, you’ll get the next error in the JS console: Can’t bind to ‘card’ since it isn’t a known property of ‘app-card’ .. Angular is telling us that you still need to define your input in the Card component. So you can edit thusly:


import {Component, Input, OnInit} from '@angular/core';
[...]
export class CardComponent implements OnInit {
  @Input() card:any;
[...]


And let’s add your card text property to the Card component template:

[...]
<p>{{ card.text }}</p>
[...]


Let’s see how it works now:


Looks fine, but the styling is a little off. Let’s fix that by adding a new style to card.component.css :

.card {
    margin-top: 1.5rem;
}

And now it looks better:

Component Communication


Let’s add a New Card Input component that will allow you to do add notes:

ng g component NewCardInput
  create src/app/new-card-input/new-card-input.component.scss (0 bytes)
  create src/app/new-card-input/new-card-input.component.html (33 bytes)
  create src/app/new-card-input/new-card-input.component.spec.ts (672 bytes)
  create src/app/new-card-input/new-card-input.component.ts (300 bytes)
  update src/app/app.module.ts (593 bytes)


And add this next to its template:

<div>
  <div>
    <input placeholder="Take a note...">
  </div>
</div>


Next, add this to the component decorator:

[...]
@Component({
  selector: 'app-new-card-input',
[...]
  host: {'class': 'col-4'}
})
[...]


And add your new component to the AppComponent template:

[...]
<div>
  <div>
    <app-new-card-input></app-new-card-input>
  </div>
</div>
<app-card-list [cards]="cards"></app-card-list>


Let’s take a look at the browser.


The problem is that your new component is not doing anything. Let’s make it work – by adding a variable that will hold your new card:

[...]
export class NewCardInputComponent implements OnInit {
[...]
public newCard: any = {text: ''};
[...]


How do you populate it with your input? If you have worked with AngularJS before, you may know the concept of two-way data binding. Or, you might have seen it in all those fancy AngularJS demos, where you input value to input and it updates the page content for you.

Here’s an interesting tidbit: Two-way data binding is no longer with you in Angular. But that doesn’t mean you have lost access to the behavior. You already saw and used [value]=”expression”, which binds the expression to the input element’s value property. But you also have (input)=”expression”, a declarative way of binding an expression to the input elements input event. Together they can be used thusly:

<input [value]="newCard.text" (input)="newCard.text = $event.target.value">

So, every time your newCard.text value changes, it’ll be passed to your component input. And every time the user inputs data into your input and the browser outputs input $event, you assign your newCard.text to the input value.


One more thing before you implement it: This input looks like a little much, doesn’t it? Actually, Angular gives us a little syntax sugar for it, which you can use here, so started from a different angle to explain how this sugar works.

<input placeholder="Take a note..." [(ngModel)]="newCard.text">

This syntax,( [ ] ), called banana in a box or ngModel, is the Angular directive that takes care of getting value out of events and all that. So you can just write a simpler code that takes your value and binds it to both the value of the input and your variable in code.

Unfortunately, after you added ngModel, you are getting the error, Can’t bind to ‘ngModel’ since it isn’t a known property of ‘input’. You need to import ngModel to your AppModule. But from where? If check the documentation, you can see that it’s in the Angular Forms module. So you need to AppModule thusly:


[...]
import {FormsModule} from "@angular/forms";
@NgModule({
[...]
  imports: [
    BrowserModule,
    FormsModule
  ],
[...]

Working with native events

So you have your variable populated, but you still, need to send that value to the card list in AppComponent. For communicating data to the component Angular, you must have input. It seems that to communicate data outside the component, you have output, and you use it, in the same way, you would use input— import it from the Angular code and use a decorator to define it:

import {Component, EventEmitter, OnInit, Output} from '@angular/core';
[...]
export class NewCardInputComponent implements OnInit {
[...]
@Output() onCardAdd = new EventEmitter<string>();
[...]
}



But there is more than just output; you also define something called EventEmitter because the component output is supposed to be an event, but you shouldn’t think about it the same way you did those old JavaScript events. They aren’t bubbles. You don’t need to call preventDefault in every event listener. To send data from the component, you should use its payload. So you need to subscribe to the events—how do you do that? Let’s change the AppComponent template:


<app-new-card-input (onCardAdd)="addCard($event)"></app-new-card-input>


You are also binding an expression to the event onCardAdd, just as you mentioned in our NewCardInput component. Now you need to implement the addCard method on your AppComponent.

[...]
export class AppComponent {
[...]
addCard(cardText: string) {
  this.cards.push({text: cardText});
}



But you’re still not outputting it from anywhere. Let’s try to make it happen when the user hits the enter key. You need to listen for the DOM keypress event in your component as well as output the Angular event triggered by that. For listening to DOM events, Angular gives you the HostListener decorator. It’s a function decorator that takes the name of a native event you want to listen for as well as the function Angular wants to call in response to it. Let’s implement it and discuss how it works:


import {Component, EventEmitter, OnInit, Output, HostListener} from '@angular/core';
[...]
export class NewCardInputComponent implements OnInit {
[...]
@HostListener('document:keypress', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
  if (event.code === "Enter" && this.newCard.text.length > 0) {
    this.addCard(this.newCard.text);
   }
}
[...]
addCard(text) {
  this.onCardAdd.emit(text);
  this.newCard.text = '';
}
[...]

So, if the document:keypress event happens, you check that the key pressed was Enter and your newCard.text has something in it. After that, you can call your addCard method, in which you output Angular onCardAdd with text from your card and reset the card text to an empty string so the user can continue to add new cards without editing the old card’s text.

Working with Forms

There are a couple of approaches to working with forms in Angular—one is template-driven and you are already using the most valuable part of it: ngModel for two-way binding. But forms in Angular are not only about model values but also about validity. Currently, you check for the validity of NewCardInput in your HostListener function. Let’s move it to a more template-driven form. For that, you can change the template for your component:

<form novalidate #form="ngForm">
  <input placeholder="Take a note..." name="text" [(ngModel)]="newCard.text" required>
</form>

Here’s another syntax sugar from Angular. The hash #form is a template reference variable that you can use to access your form out of your code. Let’s use it to make sure you actually use the required attribute validation instead of the manual check on value length:

import {Component, EventEmitter, OnInit, Output, HostListener, ViewChild} from '@angular/core';
import {NgForm} from '@angular/forms';
[...]
export class NewCardInputComponent implements OnInit {
[...]
@ViewChild('form') public form: NgForm;
[...]
  @HostListener('document:keypress', ['$event'])
  handleKeyboardEvent(event: KeyboardEvent) {
    if (event.code === "Enter" && this.form.valid) {
[...]

One more new decorator is here: ViewChild. Using that, you can access any element marked by template reference value—in this case, your form, as well as you actually, declare it as your Component public variable form, so you can write this.form.valid.

Working with template-driven forms is absolutely the same as you did before with simple HTML forms. But if you need something more complex, there is a different kind of form for that case in Angular: reactive. You’ll cover what they react on after converting your form. For that, let’s add a new import to AppModule.

[...]
import {FormsModule, ReactiveFormsModule} from "@angular/forms";
[...]
imports: [
[...]
ReactiveFormsModule,
]
[...]

Reactive forms are defined in code instead of template-driven forms, so let’s change the NewCardInput component code:

[...]
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
[...]
export class NewCardInputComponent implements OnInit {
[...]
newCardForm: FormGroup;
constructor(fb: FormBuilder) {
  this.newCardForm = fb.group({
    'text': ['', Validators.compose([Validators.required, Validators.minLength(2)])],
  });
}
[...]
if (event.code === "Enter" && this.form.valid) {
   this.addCard(this.newCardForm.controls['text'].value);
[...]
addCard(text) {
  this.onCardAdd.emit(text);
  this.newCardForm.controls['text'].setValue('');
}


In addition to importing new modules, some new things are happening here. First of all, you are using dependency injection for FormBuilder on your constructor and also building your form with it. The text there is a name of your field, an empty string is the initial value, and Validators.compose obviously allows you to combine multiple validators on a single field. You use
.value  and .setValue(”)  to access value for your field.

Let’s look at your markup for this new way of working with forms:

<form [formGroup]="newCardForm" novalidate>
  <input placeholder="Take a note..." name="text" formControlName="text">
</form>


You are using FormGroupDirective to tell Angular what form group Angular needs to look in for its definition. By using formControlName, you are telling Angular what field in the reactive form you should use.

For now, the main difference between the previous approach with template-driven forms and the new approach with reactive forms is in more coding on the reactive side. Is it really worth it, if you don’t need to define the form dynamically?

It absolutely is. To understand how it may be helpful, let’s discuss why this approach is called “reactive” in the first place.

Let’s start by adding additional code to your NewCardInput component constructor:

import { takeWhile, debounceTime, filter } from 'rxjs/operators';
[...]
this.newCardForm.valueChanges.pipe(
    filter((value) => this.newCardForm.valid),
  debounceTime(500),
  takeWhile(() => this.alive)
).subscribe(data => {
   console.log(data);
});


Open the browser and developer tools console, and watch what will happen when you input new value into your input

RxJS


So what’s actually happening here? You are seeing RxJS in action. Let’s discuss it. I guess you all know at least something about promises as well as building asynchronous code. Promise handling a single event. You ask the browser to make POST, for example, and it returns you a promise. RxJS operates with Observables, which handle streams of events.

Think about that like this: You have just implemented code that is called on every change of your form. If you process user changes with promises, only the first user change will be processed before you need to resubscribe. The Observable, at the same time, is able to process every event in a virtually endless stream of “promises.” You can break that by getting some error along the way or by unsubscribing from the Observable.

What is takeWhile here? You are subscribing to your Observables in your components. They are used in different parts of your app, so they may be destroyed along the way—for example, when you use components as pages in your routing. But while the promise in place of the Observable will run only a single time and will be disposed after that, the Observable is built to last as long as the stream is updating and you don’t unsubscribe. So your subscription needs to be unsubscribed (if you are not looking for memory leaks) like this:

const subscription = observable.subscribe(value => console.log(value));
[...]
subscription.unsubscribe();

But in your app, you have a lot of different subscriptions. Do you need to do all that boilerplate code? Actually, you can cheat and use the takeWhile operator. By using it you make sure that your stream will stop emitting new values as soon as this.alive becomes false and you just need to set that value in the onDestroy function of your component.

Summary

So this was your first Angular 5 App. In this article, you get to know about Angular 5, Typescript and Angular CLI as well as how to build your app in Angular 5. With the help of this, you can learn App composition in angular, component communication and work with native events as well as Angular forms.

It will be continued with Connecting Angular with Firebase in the next article.

If you want to develop an app with angular or any other technology and it seems difficult, there is no issue Codersera is here to help you by providing the top coder for your project:- Click here to Hire A Coder

And if you belong to the ones who are passionate about coding, Codersera can give you the opportunity to work on interesting and challenging projects. All you need to do is:- Click here to Apply As Coder

Categories
Frontend Developers Javascript React Developers React Native Developers React Native Web Resume Top Coder

A happy Struggle with React-Native-Web.


React Native Web

React-native-web is one of the most amazing idea for UI developers, it makes a longtime dream in a reality: the ability to create an application that runs on both phones and browsers with just one codebase.

React-native-web helps us to write the same React code for both React and React Native.

It makes life much easier, and although it has it’s limitations and signs, it’s a great approach for building multi-platform apps.

The path we followed to arrive at this point is also really attractive:

  • First, React appeared and changed the way we think about creating web apps.
  • Secondly, React Native released, taking all the good from React and making it accessible to iOS and Android apps. React Native basically create to work on mobile platforms, and it is highly affected by the way native apps are developed.
  • Finally, react-native-web created to take those React-Native applications and make them run in browsers again. It is the upgraded version of them. In react Native Web, the developer can easily build the websites.

— React Native Web- UI language —

The first reason is that React Native Web uses a kind of subset of React to generate the UI (User Interface). If we want a code that runs on both mobile and web, we should stick with the more restrictive one; in this case, it’s React Native.

As long as we don’t use modules that require some native functionality, a React Native app should work in browsers through react-native-web out of the box.

The second reason  is that React Native Web is a pure UI language. It defines some base components that define UI primitives, and those are thought to be independent of the platform that runs them. The libraries we can use to develop a react-native-web app.


React Native libraries…

  • On the one hand, we have React Native libraries. We should be able to take these libraries and plug them into our react-native-web project with no issue (unless they run native code or have native dependencies).
  • Unfortunately, the performance used to be the main focus among React Native Web developers  and the developers can achieve the best UI performance in the website when rendering is taken to the native side.
  • In this way, the developer can make characters in the JavaScript thread without changing the responsiveness of the interface. Those libraries with native code can’t be used in a react-native-web project. As well as, React Native libraries don’t need to be bundled to work for mobile.
  • So we need to add exceptions into our web pack’s module configuration in order to take them into the bundling. React Native libraries don’t need to be bundled to work for mobile, so we need to add exceptions into our web pack’s module configuration in order to take them into the bundling.


React libraries…

  • On the other hand, the React libraries, which generally thought to work in browsers. They make use of HTML tags to structure the UI; thus, if we use them in our universal app, they will break the mobile version.
  • If you are a React library developer, and you think your library would make sense for mobile applications, you should know it’s possible to make it work in React Native as well by using the same primitives as React Native through react-primitives.
  • Even when we find a React Native library that’s compatible with web, the process of making it work in our web app is not straightforward. In order to build our web apps, we use web pack as the bundler. And it usually doesn’t transpile the files inside our node_modules folder.

The struggle is a part of everyone’s life and it is all on the people that how they handle their struggle and face the challenges. It is on the human nature that how positively they can handle their challenges and how they fight with their struggling life. As a web developer, there are so many things that should be noted and some challenges that are given below.

Challenges face the React-Native-web Developer

5 common challenges faced by web developers:

1. Scalability

  • Scalability is a difficult thing for web developers to manage. It is load balancing between the servers, hence when the load increases when more traffic on the page. And the additional servers that added to balance it.
  • As well as all the load should not be throw on a single server instead of which the software should be design in such a way that it can work on multiple servers. Service-oriented architecture helps developers in managing and improving scalability.

2. Knowledge of Structure & Platforms

  • Frameworks are boost performance, offer libraries of coding and extend abilities. So, the developers need not do hand-coding web applications from the ground up.
  • Frameworks offer features like models, APIs, snippets of code and other elements to develop effective web applications.

3. UI/UX

  • In the era of smartphones, the web developer expected to develop UI/UX that responsive and user-friendly. If the web applications frustrate users, then it is difficult to maintain the customer’s loyalty on your website.
  • Secondly, Website navigation another part often neglected by developers. Intuitive navigation creates a better user experience for the website visitor.

4. Performance

  • Slow web applications are a failure and as an outcome, clients escape your website, thus damaging your revenue as well as reputation.
  • Some of the performance issues developer faces are Poorly written code, Un-Optimized Databases, Unmanaged Growth of data, Traffic spikes, Poor load distribution, Default configuration, Troublesome third party services, etc.

5. Security

  • Security is something the web developers need to consider at every stage of SDLC (software development life cycle). There are many things to consider when it comes to web application security.
  • Such as a denial of service attacks, the protection of user data, database malfunctioning, unofficial access to restricted parts of the website, etc.

Topics you must read to know more about React Native Web:

___CONCLUSION___

The challenges that faced by the developers are like the struggles, that every React Native Developer have to face, accept with happiness. As well as the developer who takes these struggles in a positive way is the top developers.

As a developer, you should always believe that nothing is impossible whether it is coding or assigning the whole project by own. According to the market, React-Native-Web is the most demanding and upgraded version of React and React Native.

The all-over thing that should keep in every developer mind that, Web developers are responsible for far more than just building web pages. It is also good to form your career as a web developer, freelancer or remote workers for the company. As the React Native Web is the exclusive and best way to create any website the demand of the developer is the same.

It is like a trend that new technology makes more demand in the market. In freelancing and remote workers the company found the best and top coders of React-Native-web.

Categories
Angular Frontend Developers Javascript React Developers React Native Developers React Native Web ReactJS Remote developer Top Coder

ReactJS v/s AngularJS

It is really important to choose the right platform where you should develop your web applications. ReactJS or AngularJS which framework is more important to build the application. Before talking about the contrasts that both have here is the brief introduction given below to simplify the concept of ReactJS and AngularJS. They both are well-known program developing languages that help coders or developers to build an application or websites.

ReactJS vs AngularJS

reactjs vs angularjs


Although, there are a lot of frameworks that help you in building the website. And each framework has its own strengths and qualities which could be used for a particular web application. AngularJS and ReactJS are the most popular frameworks for building a web application. And the difference between these two topics is really interesting. And they also make it hard for the web app developers and entrepreneurs to choose one for their project. There are many JavaScript frameworks available that developers or programmers can choose from, to build an amazing and innovative web application.

AngularJS

angularjs

AngularJS is a JavaScript Web application framework originally created by Google, and it is actively supported by Google and a wide community of developers. These two factors makes Angular a great platform for web applications.

AngularJS is comprehensive, which directly means that it is so familiar with MVC or knockout or cappuccino, even the developers have no trouble learning Angular testing API. As well as, it is a complete solution for rapid front-end development, so the developer doesn’t need a plug-in to build or create any data-driven web application.

◾ The interesting facts behind AngularJS:

  • The innovative idea behind the Angular is to combine all the well-known components, designs, patterns, and development practices into a single framework which is known as ‘single page application’ (SPA).
  • As well as to achieve this, AngularJS support standardized components such as the models, views, controllers, and services. And this Lead to angular making use of two important software design patterns:

    1. Model View Controller (MVC) and
    2. Dependency Injection.
  • The AngularJS is best because developing web applications with AngularJS is fast. And developers can easily use the AngularJS framework.
  • There are so many developers who use Angular to build their web applications. Besides that, Angular makes use of many ideas including, balancing modularity and complexity, being a few.
  • Angular is also updated with the latest versions too, where Angular8 being the current version, which is very powerful. It just the same, how we update our mobile applications with better and advanced features.

ReactJS

reactjs

ReactJS is one of the most popular frameworks for developing web applications, which attracted a large and active community. React consist of reusable components that will save the time of developers, while coding, helping the developers in writing modular codes. As we all know that Facebook created React, and chooses a design different from AngularJS but implements MVC in a different way than AngularJS.

ReactJS is cooler than Angular because there is no particular structure for applications built with ReactJS. React is used from website development to mobile application development using React-Native, based entirely on React. Making it an allrounder in the development field.

◾ The impressive facts behind ReactJS:

  • With React JS, developers can build the application around discrete components, with each handling its own rendering as well as their state.
  • React is fast and easy to develop UI/UX because it minimizes the number of writes to DOM(the slowest part of any client-side application) on each update, switching Browser DOM with Virtual DOM.
  • In order to implement less data flow to React, Facebook designed its own application architecture called flux. But other libraries like Redux, etc. are also quite popular.
  • Flux controls the flow of data to react component through one control point which is the dispatcher. So, flux dispatcher receives an object which is called action and allows it to an appropriate store, which then updates the global state.
  • Secondly, there are three ways of using ReactJS, which developers use to design different platform application i.e.

    – First, React
    – Second, React Native and
    – Third, React Native Web
  • Although it is recommended to write the react code using JSX – (an extension to JavaScript which directly donates components as HTML elements), but other alternative approaches are also available.

Difference between ReactJS and AngularJS.

It is quite difficult to relate the most compatible programming frameworks to each other. There are many aspects where both are equally good. Sometimes it is impossible for the developers to choose which one is better, so they try to learn both the framework. Although there are some major and impactful differences between ReactJS and AngularJS, which will help you to choose the right one according to your needs.

The different Scalability:

scalability
  • The first difference between AngularJS and ReactJS is AngularJS as a framework is easier to scale. It has its own limits and checks on how things are done which is the plus point of the AngularJS.
  • With its clearly-defined boundaries, it is easier to understand the right way of doing things in AngularJS, as it closely implements MVC. Also following the best practices in Angular is easier, compared to the React. 
  • As well as, in React, there are a lot of ways to do the same thing that makes it confusing and hard to follow best practices. There are a lot of parts that you need to figure out yourself when using React, parts which are easily clear in Angular.

Let’s talk about their Compatibility:

compatibility
  • Compatibility is the second major difference between them. With AngularJS if developers or coders have an existing code with a lot of 3rd party libraries. You as a developer may have to rebuild each and everything, whereas React is really very flexible. React can be used wherever you need it.
  • Also, it is essential to note that the AngularJS takes JavaScript into HTML projects with the help of a real DOM client-side version. On the other hand, the React JS framework does the same by including the use of a virtual DOM client-side version.
  • Another thing that should be noted is that the data binding in the Angular JS is two-way, while the type of data binding in React is one-way binding.

Know the Community Support

support
  • The third difference of this is, React is easier to use than AngularJS as we are saying from the beginning.
  • And is just because React makes it easier or the developers to pass data chunks to different parts of the application. But these things are not possible in Angular.
  • React is one of the most popular frameworks on the web to design, to create, to develop the applications. Whereas Angular is trying to catch up. But it is simpler to find the reusable code for the React than for Angular.

Think Beyond the Web:

  • The fourth difference is React has React Native and Angular has Ionic for structure Native apps for mobile devices. There always debate which is better than the other, but they are relatively equal.
  • React Native is still considered faster and more constant. If needed an all-in-one solution, go with Angular, but if you want to incrementally improve your application existing codebase, developers sometimes go with React.

The simplicity of Code:

  • The fifth most important difference is AngularJS drives with the template approach with HTML, which creates the code shorter and easier to recognize in the program.
  • React, on the other hand, has the “HTML written in JavaScript”, which can be complicated sometimes. Both AngularJS and ReactJS are great with their component structure and the problem they are trying to solve.
  • The choice between both can be based on your existing code, which is in need according to the developer’s preference.

Know the Development Time:

  • The sixth difference is the development time in AngularJS is relatively fast, mostly because of the way it is organized. There is less confusion about the best approach to do assure things, whereas in React this can be boring sometimes.
  • Setting up a new project is quicker in Angular with its boilerplate and CLI. Whereas, In ReactJS you can find many resources and projects that can help you do it faster. But still, require a lot of experiments. If you are planning to set up everything from scratch in either of the technologies.
  • The size of the React core file is smaller than Angular and Angular contains a lot of code out of the box that you might not even use. React is a library, so optimizing the code is more flexible than Angular.

Fixing the Code:

  • Last difference but not least, Debugging the code in React is much more effective. Because it catches errors with line numbers while compilation and Angular only break while it runs on the browser, which can be difficult to debug.
  • Angular has two-way data binding, which can be helpful as you can send data from children to its parents and vice versa. But it can give a lot of headaches while fixing.
  • In React, the data flows just one way, making it easier to catch the break with ease with the loss of two-way data flow at the same time.

SUMMARY

The ReactJS and the AngularJS both are strong and comparative excellent in their own framework and library. There is no doubt between their compatibility that the developers of both programming language have demand in the market.

Future of AngularJS and ReactJS is– now Angular 8 is the latest version for Angular. This is a huge step up from AngularJS. Most of the changes are behind the scenes. The update from AngularJS to Angular 8 did not change how the coder code. Now Google introducing Angular8 in the market which is the advanced version of Angular. These show how the Angular improve itself from time to time.

And Facebook is working on React Fiber, which is an update to its core system. This will increase the performance of React, add more support for animation, layout, and gestures by adding a lot of new functionalities for developers.

There are many companies where demand for ReactJS and AngularJS is still on high. As they both are really good in their working space. Also, you can read the interview questions on Angular, which is helpful to crack the major interviews of Angular. Also, the new technology named React-Native-Web.
Here you can read all the top questions on React-Native-Web interview questions, the developers are also in demand in the companies.

Hire a coder
or
Apply as a coder