Categories
Javascript Uncategorized

23+ Advanced JavaScript Interview Questions (ANSWERED)


Hungry for more advanced and tricky JavaScript Interview questions and answers to transform yourself from a Junior JavaScript Developer into a Senior JavaScript Guru before your next tech interview? Search no more! Come along and explore top hardest JavaScript Interview Questions and Answers including ES6, ES2015 for experienced web developer and get your next six-figure job offer.

Q1: Explain equality in JavaScript

Topic: JavaScript
Difficulty: ⭐

JavaScript has both strict and type–converting comparisons:

  • Strict comparison (e.g., ===) checks for value equality without allowing coercion
  • Abstract comparison (e.g. ==) checks for value equality with coercion allowed
var a = "42";
var b = 42;

a == b;            // true
a === b;        // false

Some simple equalityrules:

  • If either value (aka side) in a comparison could be the true or false value, avoid == and use ===.
  • If either value in a comparison could be of these specific values (0, "", or [] — empty array), avoid == and use ===.
  • In all other cases, you’re safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

🔗 Source: FullStack.Cafe

Q2: Provide some examples of non-bulean value coercion to a boolean one

Topic: JavaScript
Difficulty: ⭐⭐⭐

The question is when a non-boolean value is coerced to a boolean, does it become true or false, respectively?

"" (empty string)
0, -0, NaN (invalid number)
null, undefined
false

The specific list of “falsy” values in JavaScript is as follows:

Any value that’s not on this “falsy” list is “truthy.” Here are some examples of those:

"hello"
42
true
[ ], [ 1, "2", 3 ] (arrays)
{ }, { a: 42 } (objects)
function foo() { .. } (functions)

🔗 Source: FullStack.Cafe

Q3: What is IIFEs (Immediately Invoked Function Expressions)?

Topic: JavaScript
Difficulty: ⭐⭐⭐

It’s an Immediately-Invoked Function Expression, or IIFE for short. It executes immediately after it’s created:

(function IIFE(){
    console.log( "Hello!" );
})();
// "Hello!"

This pattern is often used when trying to avoid polluting the global namespace, because all the variables used inside the IIFE (like in any other normal function) are not visible outside its scope.

🔗 Source: stackoverflow.com

Q4: When should I use Arrow functions in ES6?

Topic: JavaScript
Difficulty: ⭐⭐⭐

I’m now using the following rule of thumb for functions in ES6 and beyond:

  • Use function in the global scope and for Object.prototype properties.
  • Use class for object constructors.
  • Use => everywhere else.

Why use arrow functions almost everywhere?

  • Scope safety: When arrow functions are used consistently, everything is guaranteed to use the same thisObject as the root. If even a single standard function callback is mixed in with a bunch of arrow functions there’s a chance the scope will become messed up.
  • Compactness: Arrow functions are easier to read and write. (This may seem opinionated so I will give a few examples further on).
  • Clarity: When almost everything is an arrow function, any regular function immediately sticks out for defining the scope. A developer can always look up the next-higher function statement to see what the thisObject is.

🔗 Source: stackoverflow.com

Q5: What are the differences between ES6 class and ES5 function constructors?

Topic: JavaScript
Difficulty: ⭐⭐⭐

Let’s first look at example of each:

// ES5 Function Constructor
function Person(name) {
  this.name = name;
}

// ES6 Class
class Person {
  constructor(name) {
    this.name = name;
  }
}

For simple constructors, they look pretty similar.

The main difference in the constructor comes when using inheritance. If we want to create a Student class that subclasses Person and add a studentId field, this is what we have to do in addition to the above.

// ES5 Function Constructor
function Student(name, studentId) {
  // Call constructor of superclass to initialize superclass-derived members.
  Person.call(this, name);

  // Initialize subclass's own members.
  this.studentId = studentId;
}

Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;

// ES6 Class
class Student extends Person {
  constructor(name, studentId) {
    super(name);
    this.studentId = studentId;
  }
}

It’s much more verbose to use inheritance in ES5 and the ES6 version is easier to understand and remember.

🔗 Source: github.com/yangshun

Q6: Explain Function.prototype.bind.

Topic: JavaScript
Difficulty: ⭐⭐⭐

Taken word-for-word from MDN:

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

In my experience, it is most useful for binding the value of this in methods of classes that you want to pass into other functions. This is frequently done in React components.

🔗 Source: github.com/yangshun

Q7: What’s a typical use case for anonymous functions?

Topic: JavaScript
Difficulty: ⭐⭐⭐

They can be used in IIFEs to encapsulate some code within a local scope so that variables declared in it do not leak to the global scope.

(function() {
  // Some code here.
})();

As a callback that is used once and does not need to be used anywhere else. The code will seem more self-contained and readable when handlers are defined right inside the code calling them, rather than having to search elsewhere to find the function body.

setTimeout(function() {
  console.log('Hello world!');
}, 1000);

Arguments to functional programming constructs or Lodash (similar to callbacks).

const arr = [1, 2, 3];
const double = arr.map(function(el) {
  return el * 2;
});
console.log(double); // [2, 4, 6]

🔗 Source: github.com/yangshun

Q8: Explain the difference between Object.freeze() vs const

Topic: JavaScript
Difficulty: ⭐⭐⭐

const and Object.freeze are two completely different things.

  • const applies to bindings (“variables”). It creates an immutable binding, i.e. you cannot assign a new value to the binding.
const person = {
    name: "Leonardo"
};
let animal = {
    species: "snake"
};
person = animal; // ERROR "person" is read-only
  • Object.freeze works on values, and more specifically, object values. It makes an object immutable, i.e. you cannot change its properties.
let person = {
    name: "Leonardo"
};
let animal = {
    species: "snake"
};
Object.freeze(person);
person.name = "Lima"; //TypeError: Cannot assign to read only property 'name' of object
console.log(person);

🔗 Source: stackoverflow.com

Q9: What is generator in JS?

Topic: JavaScript
Difficulty: ⭐⭐⭐

Generators are functions which can be exited and later re-entered. Their context (variable bindings) will be saved across re-entrances. Generator functions are written using the function* syntax. When called initially, generator functions do not execute any of their code, instead returning a type of iterator called a Generator. When a value is consumed by calling the generator’s next method, the Generator function executes until it encounters the yield keyword.

The function can be called as many times as desired and returns a new Generator each time, however each Generator may only be iterated once.

function* makeRangeIterator(start = 0, end = Infinity, step = 1) {
    let iterationCount = 0;
    for (let i = start; i < end; i += step) {
        iterationCount++;
        yield i;
    }
    return iterationCount;
}

🔗 Source: stackoverflow.com

Q10: When should we use generators in ES6?

Topic: JavaScript
Difficulty: ⭐⭐⭐

To put it simple, generator has two features:

  • one can choose to jump out of a function and let outer code to determine when to jump back into the function.
  • the control of asynchronous call can be done outside of your code

The most important feature in generators — we can get the next value in only when we really need it, not all the values at once. And in some situations it can be very convenient.

🔗 Source: stackoverflow.com

Q11: Explain what is hoisting in Javascript

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

Hoisting is the concept in which Javascript, by default, moves all declarations to the top of the current scope. As such, a variable can be used before it has been declared.

Note that Javascript only hoists declarations and not initializations.

🔗 Source: https://github.com/kennymkchan

Q12: What will be the output of the following code?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

var output = (function(x) {
  delete x;
  return x;
})(0);

console.log(output);

Above code will output 0 as output. delete operator is used to delete a property from an object. Here x is not an object it’s local variable. delete operator doesn’t affect local variable.

🔗 Source: github.com/ganqqwerty

Q13: What will be the output of the following code?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

var Employee = {
  company: 'xyz'
}
var emp1 = Object.create(Employee);
delete emp1.company
console.log(emp1.company);

Above code will output xyz as output.
Here emp1 object got company as prototype property.
delete operator doesn’t delete prototype property.

emp1 object doesn’t have company as its own property. You can test it like:

console.log(emp1.hasOwnProperty('company')); //output : false

However, we can delete company property directly from Employee object using delete Employee.company or we can also delete from emp1 object using __proto__ property delete emp1.__proto__.company.

🔗 Source: github.com/ganqqwerty

Q14: Explain the Prototype Design Pattern

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

The Prototype Pattern creates new objects, but rather than creating non-initialized objects it returns objects that are initialized with values it copied from a prototype – or sample – object. The Prototype pattern is also referred to as the Properties pattern.

An example of where the Prototype pattern is useful is the initialization of business objects with values that match the default values in the database. The prototype object holds the default values that are copied over into a newly created business object.

Classical languages rarely use the Prototype pattern, but JavaScript being a prototypal language uses this pattern in the construction of new objects and their prototypes.

🔗 Source: dofactory.com

Q15: What is the Temporal Dead Zone in ES6?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

In ES6 let and const are hoisted (like var, class and function), but there is a period between entering scope and being declared where they cannot be accessed. This period is the temporal dead zone (TDZ).

Consider:

//console.log(aLet)  // would throw ReferenceError

let aLet;
console.log(aLet); // undefined
aLet = 10;
console.log(aLet); // 10

In this example the TDZ ends when aLet is declared, rather than assigned.

🔗 Source: github.com/ajzawawi

Q16: Can you describe the main difference between a .forEach loop and a .map() loop and why you would pick one versus the other?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

To understand the differences between the two, let’s look at what each function does.

forEach

  • Iterates through the elements in an array.
  • Executes a callback for each element.
  • Does not return a value.
const a = [1, 2, 3];
const doubled = a.forEach((num, index) => {
  // Do something with num and/or index.
});

// doubled = undefined

map

  • Iterates through the elements in an array.
  • “Maps” each element to a new element by calling the function on each element, creating a new array as a result.
const a = [1, 2, 3];
const doubled = a.map(num => {
  return num * 2;
});

// doubled = [2, 4, 6]

The main difference between .forEach and .map() is that .map() returns a new array. If you need the result, but do not wish to mutate the original array, .map() is the clear choice. If you simply need to iterate over an array, forEach is a fine choice.

🔗 Source: github.com/yangshun

Q17: What’s the difference between a variable that is: null, undefined or undeclared? How would you go about checking for any of these states?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐

Undeclared variables are created when you assign a value to an identifier that is not previously created using var, let or const. Undeclared variables will be defined globally, outside of the current scope. In strict mode, a ReferenceError will be thrown when you try to assign to an undeclared variable. Undeclared variables are bad just like how global variables are bad. Avoid them at all cost! To check for them, wrap its usage in a try/catch block.

function foo() {
  x = 1; // Throws a ReferenceError in strict mode
}

foo();
console.log(x); // 1

A variable that is undefined is a variable that has been declared, but not assigned a value. It is of type undefined. If a function does not return any value as the result of executing it is assigned to a variable, the variable also has the value of undefined. To check for it, compare using the strict equality (===) operator or typeof which will give the 'undefined' string. Note that you should not be using the abstract equality operator to check, as it will also return true if the value is null.

var foo;
console.log(foo); // undefined
console.log(foo === undefined); // true
console.log(typeof foo === 'undefined'); // true

console.log(foo == null); // true. Wrong, don't use this to check!

function bar() {}
var baz = bar();
console.log(baz); // undefined

A variable that is null will have been explicitly assigned to the null value. It represents no value and is different from undefined in the sense that it has been explicitly assigned. To check for null, simply compare using the strict equality operator. Note that like the above, you should not be using the abstract equality operator (==) to check, as it will also return true if the value is undefined.

var foo = null;
console.log(foo === null); // true
console.log(typeof foo === 'object'); // true

console.log(foo == undefined); // true. Wrong, don't use this to check!

As a personal habit, I never leave my variables undeclared or unassigned. I will explicitly assign null to them after declaring if I don’t intend to use it yet. If you use a linter in your workflow, it will usually also be able to check that you are not referencing undeclared variables.

🔗 Source: github.com/yangshun

Q18: Describe the Revealing Module Pattern design pattern

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐⭐

A variation of the module pattern is called the Revealing Module Pattern. The purpose is to maintain encapsulation and reveal certain variables and methods returned in an object literal. The direct implementation looks like this:

var Exposer = (function() {
  var privateVariable = 10;

  var privateMethod = function() {
    console.log('Inside a private method!');
    privateVariable++;
  }

  var methodToExpose = function() {
    console.log('This is a method I want to expose!');
  }

  var otherMethodIWantToExpose = function() {
    privateMethod();
  }

  return {
      first: methodToExpose,
      second: otherMethodIWantToExpose
  };
})();

Exposer.first();        // Output: This is a method I want to expose!
Exposer.second();       // Output: Inside a private method!
Exposer.methodToExpose; // undefined

An obvious disadvantage of it is unable to reference the private methods

🔗 Source: scotch.io

Q19: What’s the difference between ES6 Map and WeakMap?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐⭐

They both behave differently when a object referenced by their keys/values gets deleted. Lets take the below example code:

var map = new Map();
var weakmap = new WeakMap();

(function() {
    var a = {
        x: 12
    };
    var b = {
        y: 12
    };

    map.set(a, 1);
    weakmap.set(b, 2);
})()

The above IIFE is executed there is no way we can reference {x: 12} and {y: 12} anymore. Garbage collector goes ahead and deletes the key b pointer from “WeakMap” and also removes {y: 12} from memory. But in case of “Map”, the garbage collector doesn’t remove a pointer from “Map” and also doesn’t remove {x: 12} from memory.

WeakMap allows garbage collector to do its task but not Map. With manually written maps, the array of keys would keep references to key objects, preventing them from being garbage collected. In native WeakMaps, references to key objects are held “weakly“, which means that they do not prevent garbage collection in case there would be no other reference to the object.

🔗 Source: stackoverflow.com

Q20: Is JavaScript a pass-by-reference or pass-by-value language?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐⭐

It’s always pass by value, but for objects the value of the variable is a reference. Because of this, when you pass an object and change its members, those changes persist outside of the function. This makes it look like pass by reference. But if you actually change the value of the object variable you will see that the change does not persist, proving it’s really pass by value.

Example:

function changeStuff(a, b, c)
{
  a = a * 10;
  b.item = "changed";
  c = {item: "changed"};
}

var num = 10;
var obj1 = {item: "unchanged"};
var obj2 = {item: "unchanged"};

changeStuff(num, obj1, obj2);

console.log(num);
console.log(obj1.item);    
console.log(obj2.item);

Output:

10
changed
unchanged

🔗 Source: stackoverflow.com

Q21: How to “deep-freeze” object in JavaScript?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐⭐

If you want make sure the object is deep frozen you have to create a recursive function to freeze each property which is of type object:

Without deep freeze:

let person = {
    name: "Leonardo",
    profession: {
        name: "developer"
    }
};
Object.freeze(person); // make object immutable
person.profession.name = "doctor";
console.log(person); //output { name: 'Leonardo', profession: { name: 'doctor' } }

With deep freeze:

function deepFreeze(object) {
    let propNames = Object.getOwnPropertyNames(object);
    for (let name of propNames) {
        let value = object[name];
        object[name] = value && typeof value === "object" ?
            deepFreeze(value) : value;
    }
    return Object.freeze(object);
}
let person = {
    name: "Leonardo",
    profession: {
        name: "developer"
    }
};
deepFreeze(person);
person.profession.name = "doctor"; // TypeError: Cannot assign to read only property 'name' of object

🔗 Source: medium.com

Q22: In JavaScript, why is the “this” operator inconsistent?

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐⭐

The most important thing to understand is that a function object does not have a fixed this value — the value of this changes depending on how the function is called. We say that a function is invoked with some a particular this value — the this value is determined at invocation time, not definition time.

  • If the function is called as a “raw” function (e.g., just do someFunc()), this will be the global object (window in a browser) (or undefined if the function runs in strict mode).
  • If it is called as a method on an object, this will be the calling object.
  • If you call a function with call or apply, this is specified as the first argument to call or apply.
  • If it is called as an event listener, this will be the element that is the target of the event.
  • If it is called as a constructor with new, this will be a newly-created object whose prototype is set to the prototype property of the constructor function.
  • If the function is the result of a bind operation, the function will always and forever have this set to the first argument of the bind call that produced it. (This is the single exception to the “functions don’t have a fixed this” rule — functions produced by bind actually do have an immutable this.)

🔗 Source: stackoverflow.com

Q23: Compare Async/Await and Generators usage to achive same functionality

Topic: JavaScript
Difficulty: ⭐⭐⭐⭐⭐

  • Generator function are executed yield by yield i.e one yield-expression at a time by its iterator (the next method) where as Async-await, they are executed sequential await by await.
  • Async/await makes it easier to implement a particular use case of Generators.
  • The return value of Generator is always {value: X, done: Boolean} where as for Async function it will always be a promise that will either resolve to the value X or throw an error.
  • Async function can be decomposed into Generator and promise implementation like:

🔗 Source: stackoverflow.com

Categories
React Native Developers

React Native Bridge For iOS

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 set up communication between native platforms and React Native.

But why do we need it?

Let’s assume you want to reuse some existing Objective-C/ Swift 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 and at some point in time, to make a production-level application you will most probably 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.

Source: official react native docs

What we will learn in this article?

We will separate this article into two parts:

  • Native Modules
  • Native UI Components

Native Modules

A Native Module is just a set of javascript functions that are implemented natively for the 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 define some functions in Swift which will control the status of a torch (whether it is “on” or “off”) and we will call these functions from React Native.

Let’s start:

Before you start you should have Xcode and Node.js installed on your computer.

Open your terminal and follow along:

npx react-native init ReactNativeBridgeIos

cd ReactNativeBridgeIos

  • Now- Open ReactNativeBridgeIos.xcodeproj file in the iOS folder (It would automatically open your iOS code in Xcode).
  • Now- Create a Swift file torch.swift in the ReactNativeBridgeIos folder. It will also ask for creating a Bridge Header file- accept that- a file named ReactNativeBridgeIos-Bridging-Header.h will be created.
  • Now- Add the following line in the ReactNativeBridgeIos-Bridging-Header.h file
#import "React/RCTBridgeModule.h"

RCTBridgeModule will just provide an interface to register a bridge module where RCT is just an abbreviation of ReaCT.

Now- Open ‘Torch.swift’ and add the following code:


import Foundation
@objc(Torch) class Torch: NSObject {
  @objc static func requiresMainQueueSetup() -> Bool {return true}
  
  @objc static var isOn = false
  
  @objc func turnOn() {
    Torch.isOn = true
  }
  @objc func turnOff() {
    Torch.isOn = false
  }
  @objc func getTorchStatus(_ callback: RCTResponseSenderBlock) {
    callback([NSNull(), Torch.isOn])
  }
}

A Torch class is created which is inherited from NSObject.

NSObject: The root class of most Objective-C class hierarchies, from which subclasses inherit a basic interface to the runtime system and the ability to behave as Objective-C objects.”

source: developer.apple.com

A static variable “isOn” is created to set the status of the torch which will accept boolean values. Two functions “turnOn” and turnOff are created just to change the status of our torch. And a getTorchStatus function, which will accept a callback parameter to get the status of the torch which we will call from javascript.

RCTResponseSenderBlock” accepts only one argument – an array of parameters to pass to the JavaScript callback. And, NSNull() is passed as the first element which we have considered as an error in the callback.

A function requiresMainQueueSetup is made to make this code run on MainQueue. Else, it will give a warning about the same.

You may have already noticed that we have used “@objc” before the class and the functions (this is just to make the class, functions, or variables available to Objective-C).

Now- Create an Objective-C file named Torch.m by pressing cmd + N and add the following code:


#import <Foundation/Foundation.h>
#import "React/RCTBridgeModule.h"
@interface RCT_EXTERN_MODULE(Torch,NSObject)
RCT_EXTERN_METHOD(turnOn)
RCT_EXTERN_METHOD(turnOff)
RCT_EXTERN_METHOD(getTorchStatus: (RCTResponseSenderBlock)callback)
@end

To expose the functions of native to react javascript, we have to do that explicitly by using RCT_EXTERN_METHOD()

Now- To access the torch class from javascript, we have to import {NativeModules} from ‘react-native’. add the following code in the App.js file.


import React, {Component} from 'react';
import {StyleSheet, Text, View, NativeModules, Button} from 'react-native';
const {Torch} = NativeModules;
export default class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      isOn: false,
    };
    this.updateTorchStatus();
  }
  turnOn = () => {
    Torch.turnOn();
    this.updateTorchStatus();
  };
  turnOff = () => {
    Torch.turnOff();
    this.updateTorchStatus();
  };
  updateTorchStatus = () => {
    Torch.getTorchStatus((error, isOn) => {
      this.setState({isOn: isOn});
    });
  };
  render() {
    return (
      <View style={styles.container}>
        <Text style={{fontSize: 24}}>
          Torch is {this.state.isOn ? 'ON' : 'OFF'}
        </Text>
        {!this.state.isOn ? (
          <Button onPress={this.turnOn} title="Switch ON " color="green" />
        ) : (
          <Button onPress={this.turnOff} title="Switch OFF " color="red" />
        )}
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#d3d3d3',},
});

In the above code, the state of the torch is set by the updateTorchStatus function which is using the Native function getTorchStatus and passing a callback to it. A button is made which on pressing toggle the status of the torch in the Native code.

Now, you can start the application by running the following command:

npx react-native run-ios

You will see something like this:

After clicking the button:

So, you can see that we have created a Native Bridge for iOS.

So this is all about 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

Let’s create a Switch UI component:

  • For that open SwitchApp.xcodeproj file (from iOS folder, in Xcode just like we did in the Native Module section).
  • Then, create a SwitchView.swift file from

file (from tab bar)> new > file > Cocoa Touch Class

and name that SwitchView and also accept the “Create Bridging Header” when prompted, which will create a file SwitchApp-Bridging-Header.h. This will help to communicate between Swift and Objective C code.

Now, add the following import statements in SwitchApp-Bridging-Header.h file.


#import "React/RCTBridgeModule.h"
#import "React/RCTViewManager.h"
#import "React/RCTEventEmitter.h"

RCTBridgeModule will just provide an interface to register a bridge module where RCT is just an abbreviation of ReaCT.

Now, open ‘SwitchView.swift’ and add the following code:


import UIKit
class SwitchView: UIView {
  
  @objc var isOn: Bool = false  {
    didSet {
          button.backgroundColor = isOn ? .yellow : .black
          button.setTitle(String(describing: isOn ? "I am ON" : "I am OFF"), for: .normal)
     }
  }
  override init(frame: CGRect) {
    super.init(frame: frame)
    self.addSubview(button)
  }
  required init?(coder aDecoder: NSCoder) {
    fatalError("init has not been implemented")
  }
  lazy var button: UIButton = {
      let button = UIButton.init(type: UIButton.ButtonType.system)
      button.autoresizingMask = [.flexibleWidth, .flexibleHeight]
      button.titleLabel?.font = UIFont.systemFont(ofSize: 20)
      button.addTarget(
        self,
        action: #selector(toggleSwitchStatus),
        for: .touchUpInside
      )
      return button
    }()
  @objc func toggleSwitchStatus() {
    isOn = !isOn as Bool
  }
}

In the above code: We created a Switch View which is inherited from UIView. A boolean variable “isOn” is defined for the status of the Switch whether it is on or off. Also, color, title, size, etc. are defined.

On clicking the button the “toggleSwitchStatus” method is called, which does nothing but toggle the value of “isOn” variable to true or false.

Now, create a Switch.swift file and add the following code:


import Foundation
@objc(Switch)
class Switch: RCTViewManager {
  
  override func view() -> UIView! {
    return SwitchView()
  }
  
  override static func requiresMainQueueSetup() -> Bool {
    return true
  }
}

A Switch class inherited from RCTViewManager is created.

“Native views are created and manipulated by subclasses of RCTViewManager. These subclasses are similar in function to view controllers, but are essentially singletons – only one instance of each is created by the bridge. They expose native views to the RCTUIManager, which delegates back to them to set and update the properties of the views as necessary.”

Source: official react-native docs

A function “requiresMainQueueSetup” is made to make this code run on MainQueue. Else, it will give a warning about the same.

Now- Create an Objective-C file with the name of Switch.m and add the following code:


#import "React/RCTViewManager.h"
@interface RCT_EXTERN_MODULE(Switch, RCTViewManager)
RCT_EXPORT_VIEW_PROPERTY(isOn  , BOOL)
@end

To expose the functions of native to react javascript- we have to do that explicitly by using RCT_EXTERN_MODULE(). By that, we have exposed Switch class and properties to our javascript code.

Now, to use the Switch UI button in javascript we have to import {requireNativeComponent} from ‘react-native’,

Add the following code in the App.js file


import React, {Component} from 'react';
import {StyleSheet, View, requireNativeComponent, Text} from 'react-native';
const Switch = requireNativeComponent('Switch');
export default class App extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Switch style={styles.nativeBtn} isOn={false} />
      </View>
    );
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: 'pink',
    alignItems: 'center',
    justifyContent: 'center',
  },
  nativeBtn: {
    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 Swift and shown in the app through javascript.

Now, run the app by-

npx react-native run-ios

You will be seeing the button like this:

After clicking on it:

In this article, we have created both the Native Modules and Native UI components and use them through the react-native javascript code.
For react native bridge for android, refer this article https://codersera.com/blog/react-native-bridge-for-android/


Frequently asked questions

Categories
Development

20 App Development Trends for 2020

Apps help in improving your interaction with your mobile. With the number of mobile and tablets around the world, it has become essential for companies to develop newer apps to remain popular and provide users with the best product.

The demand for apps becomes more prominent from the fact that about 69.6% of the population of the US uses a smartphone, which is a large number.

Considering the growing need and usability amongst users of all age groups and for various business requirements, developers are continuously experimenting and developing newer apps to satiate different purposes in business, entertainment, education, etc.

Before discussing the top trends, let us have a brief overview of mobile application development.

What is App Development?

App Development

Application development is the process of creating a computer program or a set of programs to perform the different tasks that a business requires. From calculating monthly expenses to scheduling sales reports, applications help businesses automate processes and increase efficiency.

Every app-building process follows the same steps: gathering requirements, designing prototypes, testing, implementation, and integration.


These applications can be pre-installed by the manufacturer or delivered as web applications using server-side or client-side processing (e.g., JavaScript) to provide an “application-like” experience within a Web Browser.

App development is primarily done for running the applications on mobile platforms and the most common platforms being Android and iOS.

While developing an app, developers have to take care of parameters like screen size, software version, hardware specifications, and configurations due to the nail-biting competition between various software. Applications are capable of affecting people’s opinions towards the respective company.

For instance, if the application works flawlessly and user experience is good, then the consumer is more likely to use that app instead of a laggy and unresponsive app even though the company is better than the former one.

What is the need for App development?

If you own some business or if you have an online business then apps are the best possible medium reaching out to your customers. By using the app you have a direct platform to interact with consumers without any physical meeting and resulting in enhanced productivity.

Mobile and Tablet sales are increasing day by day indicating greater user engagement every single day.

Following are the major benefits of App development:

  1. Increase your Visibility – Increasing visibility means keeping the user engaged with your app as much as possible. To increase visibility, you can provide promotions and offers frequently so the user gets more engaged with your app.
  2. Establish Brand Value in the market – To establish your brand value in the market, one needs to stay connected to the consumer. And one mobile app fulfills all such business communication needs. To make your app more user-friendly, one must keep on adding better updated, useful features.
  3. Increase in Sales – For increasing sales apps are considered the best platform as they act as a direct platform between you and your consumer. If the app interface is smooth, the user-engagement gets automatically increased.
  4. Increasing Customer Loyalty – With the app, you can connect with the customer more regularly and frequently, prevailing a sense of belonging and loyalty within the user. This can be achieved by sending personalized messages and recommendations to each user, based on their preferences and last bought products.
  5. Competitive Edge – A well designed mobile app gives you an edge over your competitors who haven’t designed one yet.
  6. The Complete analysis of your customers – By running analytics of your app, you can gather information regarding customers. Information like average time spent, most viewed product, traffic on the app, and other factors that will help you in increasing your productivity.

Now that we have completed the discussion regarding App Development, let us study the important app trends for 2020:

App Development Trends

1. Blockchain TechnologyBlockchain is a simple way of transferring information from one point to another, where the transfer of data takes place in the form of blocks connected together like a chain. It makes the use of Bluetooth technology to transfer data.

It is considered very secure for the transmission of data. For instance, if one of the blocks in the chain is detected to have wrong information, then the whole network will fall. Because of this, it is used by industries like Hotels, Healthcare, etc. Applications of Blockchain are Cryptocurrencies, Financial Services, Video Games, Supply chains.

2. Internet of Things(IoT) – IoT(also known as the Internet of Things), refers to things that are connected to the internet for sharing data and these devices are embedded with sensors to collect data.

For example- Smart Dustbin is a perfect example of IoT where sensors detect humans nearby and open itself as soon as someone is nearby. Another common example of IoT is Smart Home, integrated with multiple apps operated by remote controls.

In the following graph, you can observe its rapid rise and this indicates many people shifting towards IoT in the coming years:

Internet of Things(IoT)

3.AI – Artificial Intelligence is the ability of a device to judge the surroundings or conditions around it and act on it by itself, without any human intervention. AI makes life easier for us and it is being integrated with mobile phones and apps.

For instance, Google and Apple have their software assistants who improve over time by gaining information about us. Also, are capable of giving suggestions after analyzing the user’s preferences. In simple words, Artificial Intelligence is making our phone smarter.

The usage chart of AI is shown below:

Artificial Intelligence

4. AR and VR – Since the beginning of 2019, many apps are shifting to Virtual Reality and Augmented Reality even though they aren’t related to gaming or entertainment arena.

An example of an AR-based game is The Walking Dead: Our World

Additionally, Google and Samsung have incorporated it with their phone’s cameras, indicating greater use in 2020. By using AR and VR, we can experience many things that can’t be experienced physically.

AR and VR

According to a study published in Statista 2019, the count of these apps will increase to 5 billion apps or more very soon. A popular example of this is social media apps like Snapchat and Instagram have already been using AR for a while now and other companies are expected to follow this too.

5. Mobile Wallets – With the latest advancements in technology, mobile wallets have become quite common in today’s time. The biggest plus mobile wallets bring with them is that they relieve us from carrying money and provides a hassle-free and secure way of transaction.

Mobile Wallets

The surge in mobile wallet trend is due to the expansion of the internet payment systems that require fast and more secure channels for money transactions.

6. Beacon Technology – It alerts websites when someone enters or exits the location they are placed in, making it a useful security tool.

Also, It is a great marketing tool for reducing the gap between customers and companies. Moreover, it helps in the exchange of sales in the retail sector.

For a better understanding of Beacon, you can refer to the image shown below:

Beacon Technology

7. Wearable Devices – Wearable devices have become a big market since 2019, be it is a Fitness band or smartwatches they have garnered a huge customer base. With the integration of these bands with mobile phones, users enjoy a seamless experience.

For the amount of revenue generated by the devices, you can refer to the chart below:

Wearable Devices

With big companies like Samsung and Apple launching products like Samsung Gear and Apple Watch respectively, other companies are expected to follow suit.

8. 5G Technology5G is the latest technology launched in 2019 that elevates the mobile network. It not only interconnects people but also interconnects/ control machines, objects, and other devices.

5G Technology

9. Chatbots – Chatbots are a better way of solving problems and are suitable for the “Do-it-yourself” type users. It is a great way of expanding customer relationship management and improve productivity.

With the help of chatbots, human errors can be greatly reduced and the users get the exact solution to their problem.

The graph below shows the popularity of chatbots in various countries:

Chatbots Popularity

10. Instant Apps – Instant apps are the best solution for low storage space and they take less loading time and provide better productivity. They are smaller than the normal app but provide the same functionality.

To put it in simple words, Instant apps can be considered as a trial for certain apps that users get access to without downloading them.

11. Mobile Security – Mobile Security is very important since most of our data is stored on our mobile and companies cannot afford the setback that Facebook had after the Cambridge Analytica leak. Therefore, companies investing more in cybersecurity measures.

Mobile Security

12. Cloud-integrated appsCloud technology has many advantages as it allows the user to store the data on a cloud without using the phone’s memory.

Following are a few of its advantages:

  • You can access your data securely.
  • It makes app development quicker and simpler, alongside cost savings. 
  • Cloud integrated with apps can be beneficial for both user and developer.

13. Low code development – This is going to become the biggest change in app development as it will increase the functionality and reduce the time taken to build the code.

With increasing rates of mobile app development, developing small codes will enable the developers to make code run faster.

14. Personalization – With the increasing number of apps in the market, users have become very selective in choosing the best for themselves. Keeping this in mind, companies are developing apps that provide customization and the customer is the king where he has the freedom of choosing default look or personalization.

15. Voice Search – People like to use the phone’s assistance to perform various tasks like calling, messaging and instructing on various other things. to ease out their busy work schedules.

It is helpful when the person is not close to the phone or his hands are full. Some of the common examples of Voice search devices are Google Home and Amazon Alexa.

Some statistics related to voice search are-

  • By 2024, the global voice-based smart speaker market could be worth $30 billion.
  • 60% of smartphone users have tried voice search at least once in the past 12 months.
  • Voice-based shopping is expected to jump to $40 billion in 2022
  • 55% of teenagers are using voice search daily basis.
app development trends

16. PWA – PWA gives companies the functionality to work offline and create user experience similar to native apps that run on mobiles and computer devices. Since PWA(Progressive Web App) is a type of webpage or website known as a web application, there is no need for developers/ users to install web apps via digital distribution systems like Apple App Store or Google Play.

17. Predictive Analytics – Predictive analysis makes future predictions by studying the present data. By using these analytics, you can improve your business by finding out the weak areas and improve them.

18. Foldable phones – The launch of foldable phones last year has opened a new chapter as they are very different from normal phones (they require apps specifically for them).

Although there are negligible amount of foldable phones available right now, they will become popular very quickly and that will lead to demand in apps supporting them.

An example of a foldable phone is Samsung Galaxy Fold.

19. EMM and APM– Enterprise Mobile Management (EMM)and Application Performance Management (APM)are two basic components of enterprise app development procedure. APM is capable of improving the system’s performance so it is used for quality testing. On the other hand, EPM helps companies enable the safety of mobile devices and increases the efficiency of the company.

20. AMP – AMP(Accelerated Multiple Pages) is a simple version of HTML used for increasing the loading speed of web pages. It allows developers to create web pages with high performance, quick speed, and lower bounce rates across all mobile devices.

By using AMP, load-time for medium pages has come down to 0.5 seconds and time spent by the users on pages has doubled. Because of this, the profit generated has increased to a value of $676,822 from sales conversion.

Conclusion

With all these mobile application development trends, the app industry is expected to expand at a rapid pace. The competition between developers and mobile makers will be fiercer than ever. And in 2020, this will provide a wide variety of options and facilities for users.

Categories
React Developers ReactJS

React Hooks with Typescript : UseCallback, UseMemo, UseContext And UseRef

Lets, check react advanced hooks, i.e. UseCallback, UseMemo, UseRef, and UseContext. All these come under React 16.8 version and help the user create an optimized react application.

Let’s create a react application environment for our project by using either of the following commands:   


1.yarn create react-app advanced-hooks-tutorial --template typescript
 # or 
2.npx create-react-app advanced-hooks-tutorial --template typescript

The above command will create a Project with the name “advanced-hooks-tutorial”. Once it’s done go to the directory and start the project either by “npm start” or “yarn start”.

We will be using yarn throughout this tutorial to maintain consistency.

Let’s now integrate the project with antd which is a design library by the name of antd design, that helps us to create some standard UI components. Additionally, you can use other design libraries as well if you want.

  1. Add antd to dependency
# terminal

yarn add antd

2. Add antd CSS to load stylings

# src/index.tsx

...
import 'antd/dist/antd.css';
...

That’s all for our project base, we have successfully integrated react hooks with antd design library.

UseCallback

UseCallback takes two arguments- In the first argument it takes an inline function that is called callback and in second arguments it takes an array of dependencies on which the callback function depends and returns a memoized callback.

The memoized callback changes only when one of its dependencies is changed. This is useful to optimize the child components that use the function reference from their parent component to prevent unnecessary rendering.

# syntax 

const memoizedCallback = useCallback(() => performSomething(param1, param2 ,...),[param1, param2, ...]);

Let’s see an example for this – Here, we are going to create an app consisting of two-buttons which will increment the age and salary of a person.

  • Create a file AdvancedHooksComponent.tsx in src/components directory- create the directory if not available there.
  • Now create a functional component, ie. AdvancedHooksComponent and import the component in App.tsx file.
# src/components/AdvancedHooksComponent.tsx

import React from 'react';

interface Props {
};

const AdvancedHooksComponent: React.FC<Props> = () => {

    return (
        <div>
            Advanced Hooks Component
        </div>
    );
};

export default AdvancedHooksComponent;

After this, your App.tsx file would look like :

# src/App.tsx

import React from 'react';
import './App.css';
import AdvancedHooksComponent from "./components/AdvancedHooksComponent";

const App: React.FC = () => {
  return (
    <div className="App">
        <AdvancedHooksComponent/>
    </div>
  );
};

export default App;

Now let’s add two child Button component named- AgeButton, SalaryButton, and a Title component. Import them in AdvancedHooksComponent.tsx.

# src/components/AdvancedHooksComponent.tsx

import React,{useState} from 'react'
import AgeButton from './AgeButton'
import SalaryButton from './SalaryButton'

interface Props {
};

const AdvancedHooksComponent: React.FC<Props> = () => {

    const [age, setAge] = useState(12);
    const [salary, setSalary] = useState(5000);
   
    const ageHandler = ()  => {
            setAge(age+1);
        };

    const salaryHandler = () => {
            setSalary(salary+500);
        };

    return (
        <div>
            <h1>Use CallBack Example</h1>
            <AgeButton clickHandler={ageHandler} age={age}/>
            <SalaryButton clickHandler={salaryHandler} salary={salary}/>
        </div>
    );
};

export default AdvancedHooksComponent;

We have used the useState hook to create state variables, i.e. age and salary and their corresponding dispatcher, ie. setAge and setSalary. Learn How to create State Variables.

AgeHandler and SalaryHandler are two inline functions that increment the age and salary on every click of AgeButton and SalaryButton respectively.

Note: If you don’t know how to use useState then you can refer our blog from here:- React Hooks With Typescript.

AgeButton component looks like :

# src/components/AgeButton.tsx

import React from "react";
import {Button} from "antd";

interface Props {
    clickHandler : () => void;
    age : number
}

const AgeButton = ({ clickHandler, age } : Props  ) => {
    console.log("Age Button Rendered Age = " + age)
    return (
        <Button onClick={clickHandler} type="primary" style={{ margin : 2}}>Increment Age</Button>
    )
};

export default React.memo(AgeButton);

SalaryButton component looks like :

# src.components/SalaryButton.tsx

import React from "react";
import {Button} from "antd";


interface Props {
    clickHandler : () => void;
    salary : number;
}

const SalaryButton = ({ clickHandler, salary } : Props ) => {
    console.log("Salary Button Rendered Salary = " + salary)
    return (
        <Button onClick={clickHandler} type="primary" style={{ margin : 2}}>Increment Salary</Button>
    )
};

export default React.memo(SalaryButton);

We have a console statement in both the AgeButton and SalaryButon that will help us in understanding the concept of useCallback hook later in the project.

Note: AgeButton and SalaryButton components are wrapped in the React.memo function which is a higher-order function. You can learn more about this from here:- React Memo.

Now start the app using the below command:

  yarn start

You will see the following output in the console:

Callback Example

As you can see in the web console, the rendering order of child component- first AgeButton component render and then SalaryButton component render.

Now, if we click on the increment Age Button then age will be incremented and react will re-render the component because if state changes then the component re-renders.

So the output looks like :

As you can see in the console- The AgeButton component re-render and age become 13, which is correct but the SalaryButton component also re-render and that is not necessary because we updated the age only and not salary.

So to fix this problem, useCallback comes into the picture:

We have to pass the ageHandler and salaryHandler function in the useCallback hook, so that memoized callback returns and changes only when passed dependencies changed.

For ageHandler- the only dependency is age and for salaryHandler- salary is the only dependency.

# src/components/AdvancedHooksComponent.tsx

import React, {useCallback, useState} from 'react';
import AgeButton from "./AgeButton";
import SalaryButton from "./SalaryButton";

interface Props {

}

const AdvancedHooksComponent: React.FC<Props> = () => {

    const [age, setAge] = useState(12);
    const [salary, setSalary] = useState(5000);


    const ageHandler = useCallback(()  => {
        setAge(age+1);
    }, [age])


    const salaryHandler = useCallback( () => {
        setSalary(salary+500);
    }, [salary])


    return (
        <div>
            <h1>UseCallBack Example</h1>
            <AgeButton clickHandler={ageHandler} age={age}/>
            <SalaryButton clickHandler={salaryHandler} salary={salary}/>
        </div>
    );
};

export default AdvancedHooksComponent;

Now, if I click on the increment age button only the AgeButton component will re-render.


As you can see in the console only the AgeButton component is re-rendered. So this is how useCallback helps in preventing unnecessary rendering.

UseMemo

This hook will return a memoized value.

Suppose you have to compute a value that requires complex computation like fetching the list of 500 people from a database and then map over the list and then filter some person and finally update on the UI.

This operation is costly and recomputes after every rerender.

Using useMemo, we can simplify the process and this operation is performed only once and the value is stored in the cache. And the next time you want it, you’ll get it much faster.

# syntax

const memoizedValue = useMemo( () => costlyOperation(param1 , param2, ...) , [param1, param2, ...]);

The syntax of useMemo is similar to useCallback, but both work differently- useCallback returns a memoized callback(or function), on the other hand useMemo returns a memoized value (the result of the memoized callback).

Let’s see an example for this, where I made some modifications in AdvancedHooksComponent.tsx file :

# src/components/AdvancedHooksComponent.tsx

import React, {useCallback, useState} from 'react';
import AgeButton from "./AgeButton";
import SalaryButton from "./SalaryButton";

interface Props {
}

const AdvancedHooksComponent: React.FC<Props> = () => {

    const [age, setAge] = useState(12);
    const [salary, setSalary] = useState(5000);


   const notMemoizedValue = () => {
        // some complex computation work here..
        let i = 0;
        while (i < 2000000000) i++;

        // after while break then do something here
        if(age % 2 === 0) return "Even";
        else return "Odd";
      }


    const ageHandler = useCallback(()  => {
        setAge(age+1);
    }, [age])


    const salaryHandler = useCallback( () => {
        setSalary(salary+500);
    }, [salary])


    return (
        <div>
            <h1>UseMemo Example</h1>
            <h3>{notMemoizedValue()}</h3>
            <AgeButton clickHandler={ageHandler} age={age}/>
            <SalaryButton clickHandler={salaryHandler} salary={salary}/>
        </div>
    );
};

export default AdvancedHooksComponent;

We have the “notMemoizedValue” function, which will check whether the current age is even or odd but we need some computational work to do before checking odd or even.

For simplicity, we will make a while loop that takes some time (which behave as complex computation like fetching data from database and so on). After the while loop breaks, the odd-even checking statement executes.

The result of “notMemoizedValue” function will be displayed on the UI.


So, as you can see our “notMemoizedvalue” function returns an even value but this value is not memoized value because if we press the increment salary button then the salary will be incremented. And after this rerendering occurs which leads to the recomputation of the “notMemoizedValue” function value that remains unchanged because age doesn’t change only the salary gets changed. Apart from this, you might feel some delay also.

So, Using useMemo we can return a memoized value of the “notMemoizedValue” function which saves the time from recomputation.

Using useMemo the code will look like :

# src/components/AdvancedHooksComponent.tsx


import React, {useCallback, useMemo, useState} from 'react';
import AgeButton from "./AgeButton";
import SalaryButton from "./SalaryButton";

interface Props {
}

const AdvancedHooksComponent: React.FC<Props> = () => {

    const [age, setAge] = useState(12);
    const [salary, setSalary] = useState(5000);


    const memoizedValue =  useMemo( () => {
        // some complex computation work here..
        // for simplicity I wrote while loop here 
        let i = 0;
        while (i < 2000000000) i++;

        // after while break then do something here
        if(age % 2 === 0) return "Even";
        else return "Odd";

    } , [age])

    const ageHandler = useCallback(()  => {
        setAge(age+1);
    }, [age])


    const salaryHandler = useCallback( () => {
        setSalary(salary+500);
    }, [salary])


    return (
        <div>
            <h1>UseMemo Example</h1>
            <h3>{memoizedValue}</h3>
            <AgeButton clickHandler={ageHandler} age={age}/>
            <SalaryButton clickHandler={salaryHandler} salary={salary}/>
        </div>
    );
};

export default AdvancedHooksComponent;

Simply, remove the “notMemoizedValue” function with “memoizedValue” function and save the file.

Now, if you again press the increment salary button then the memoized value of Odd-Even will be return by the “memoizedValue” function and now this time you do not feel any delay.

UseRef

Using useRef Hook, we can access the DOM nodes or HTML elements as we access in vanilla javascript via “document” object, so that we can interact with those DOM nodes.

# syntax

const nameRef = useRef(initialValue);

useRef hook takes an initial value and returns a mutable object (a mutable object means the object whose state can be changed after it is created).

The return ref object holds a mutable value in its current property which will remain the same on every rerender.

Let’s do an example for this: In the same file AdvancedHooksComponent, let’s create an input element- :

# src/components/AdvancedHooksComponent.tsx

import React, { useEffect, useRef} from 'react';

interface Props {
}

const AdvancedHooksComponent: React.FC<Props> = () => {

    const inputRef = useRef<HTMLInputElement>(null);

    useEffect(() => {

        if(inputRef && inputRef.current) {
            inputRef.current.focus();
        }

    }, [])


    return (
        <div>
            <h1>UseRef Example</h1>
            <input type="text" ref={inputRef} style={{width : '40%'}}/>
        </div>
    );
};

export default AdvancedHooksComponent;

As you can see, we have an inputRef object containing initial value as null which gets passed in the input ref attribute.

Now, save the file and go to your browser- You will see that your input field is focused and you can do other things as well, as you do in vanilla javascript by “document” object.

fig

Note: useRef does not notify you when it’s content value changes. Also changing useRef current value doesn’t lead to re-render.

UseContext

To understand the concept of useContext hook– First we have to understand what is React Context API?

React Context API helps us to pass the data down to the child components (which depends on parent for data) from the root or parent component, instead of manually passing the data to every component by using props.

Let’s look at the below picture :

Suppose, we have three above components in our project and we want to pass the username of a user from AppComponent to UserComponent without using HomeComponent in between:-

App.tsx looks like :

# src/App.tsx

import React from 'react';
import './App.css';
import HomeComponent from "./components/HomeComponent";

export const UserContext = React.createContext('');

const App: React.FC = () => {
    
    const value : string = "Codersera";

  return (
    <div className="App">
        <UserContext.Provider value={value}>
            <HomeComponent/>
        </UserContext.Provider>
    </div>
  );
};

export default App

Here, we used React.createContext API to create a Context with an empty string as the initial value. It returns two components Provider and Consumer. Learn about API.

Provider: It is used to pass the data down to the child components.

Consumer: It is used to consume the data passed by the Provider component.

Note: If you don’t use useContext hook, then you can use the Consumer component. But here we use, useContext hook for consuming the data which makes the code less and more readable.

Provider component takes an attribute called “value” through which we can pass the data down. To use the passed data value, components should be wrapped inside the UserContext component.

# src/components/HomeComponent.tsx

import React from 'react';
import UserComponent from "./UserComponent";

const HomeComponent = () => {
    return (
        <UserComponent/>
    );
};

export default HomeComponent;

HomeComponent simply just renders UserComponent.

# src/components/UserComponent.tsx

import React, { useContext} from 'react';
import { UserContext } from '../App'


const UserComponent = () => {
    const username = useContext(UserContext);
    return (
        <div>
            <h1>UseContext</h1>
             <div>{username}</div>
        </div>
    );
};

export default UserComponent;

UserComponent uses the passed data value- First it imports the UserContext Object from App.tsx file, then passes this object in the argument of useContext hook (which returns the passed data value), as we have used inside the div tag.

The output of the above code looks like :


That’s it. We have successfully used useCallback, useMemo, useRef, and UseContext.

Categories
Development

Top Game engines for Game Development

Who doesn’t love playing games? I mean, it’s the best way to pass time and keep ourselves entertained at the same time, right? We all play some type of games at some point of time, whether it is an Open-world like GTA San Andreas or a first-person shooter like Counter-Strike or Call of Duty.

But has anyone given a thought about how a game is made and what it is all about? Read more to know regarding the game engine and its role in game development and find answers to these questions as well:

  • How much development goes behind making the game?
  • All of you must have heard the term “Game Engine” but what does it mean?
  • How come the games are different when they are developed on the same engine by the same company?

Before going on to discuss the top game engines, let us have a brief description of what a game engine is all about:

What is a Game engine?

A game engine is a software which is used to design games quickly. In other words, it is a framework that brings all the essential tools required for building the games together. The main reason for using it is to reduce the cost, time, and complexity required in the development of the game.

Most of the time, It is observed that whenever there is a lag, crash or frame drop in a game, people immediately blame it on the engine. However, it’s not true. The lagging and the frame drops are caused because of the poor programming in the code.

The core functionality of the game engine includes a rendering engine(“renderer“)for 2D or 3D graphics, networking, animation, artificial intelligence, and memory management.

Most of the big gaming companies have developed their own gaming engine whereas some open-source engines are also available.

Advantages of Game Engine

  1. Most of the work like graphic designing, memory management, and audio is easily done by the game engine.
  2. It increases efficiency by reducing the amount of knowledge required by the developer.
  3. When working on a big project, it reduces the time it would have taken by writing the code.

Disadvantages of Game Engine

  1. If you are making a small game, then it is best to write the code yourself rather than leaving it for the game engine.
  2. Debugging is not easy if it isn’t open-source.

Components of Game engine

A game engine comprises of five main components:

  1. Main Game Program – It consists of the algorithms that implement the game’s logic.
  2. Rendering Engine – The job of the rendering engine is to generate animated 3D graphics.
  3. Audio engine – It consists of algorithms related to loading, modifying and output of sound through the user’s speaker. Newer Audio engines are capable of producing Doppler effect, echoes and oscillations.
  4. Physics Engine – Physics engine is used to implement the laws of physics realistically within the game.
  5. AI – AI or Artificial Intelligence is employed according to the genre of the game since each genre uses a different logic.

Now that we have discussed the engine, let us discuss Game development in short.

Game Development

Game development is the art of creating video games that are used to describe the design, development, and release of a game. It can be made by a big publishing house or a solo group of developers. It is often considered an easy task but it involves a lot of patience, algorithms, programming, and many tests before reaching the user.

Role of Gaming Engines in Game Development

The game requires an architecture according to which it has to be built and it requires tools for it. Gaming engines provide both of them by saving time and money. It makes the process easier and allows the developer to reuse lots of functionality.

Along with this, the gaming engine provides graphics and sound which leaves the development team with more time to do something else.

For instance, Rockstar’s worldwide-hit game, GTA V(Grand Auto Theft 5) was built on their own gaming engine knows as RAGE. Thanks to RAGE, they had their graphics, sound, and AI done.

There are many instances in the gaming world where two games published by the same company were very different from each other. In such cases, the difference is created because of the programming and the setting in which the game is set up.

When we talk about gaming engines for beginners, there are a lot of options available out there like:-

1. Buildbox

Buildbox

Buildbox is a No-code development program that focuses on game creation without programming, coding or scripting. It is a cross-platform software that can run on both Windows and iOS. Its important features are the image drop wheel, asset bar, options bar, collision editor, scene editor, monetization options and sliders that change the physics within the game.

2. RPG Maker

RPG Maker

RPG Maker is used in multiple game genres. It is good for designing the game and has a very simplified code. It is better suited for those who have little experience in development.

3. GameMaker Studio 2

GameMaker Studio 2

This code engine supports both 2D and 3D but is mostly used for 2D animations. It is great for animators and easy to learn. Along with that, it has many tools and resources useful for designing.

4. CopperCube 5

CopperCube 5

It is one of the simplest gaming engines to master for a beginner. It allows you to make a 3D game by joining fragmented pieces and pretty easy to use thanks to its visual editor. The only con is that it has outdated graphics.

Now that we have talked about the gaming engines for beginners, let us now talk about the top gaming engines:

1. Unity

unity

Unity is a cross-platform game engine developed by Unity Technologies. It can be used to create 3-D as well as 2-D, Virtual reality and Augmented Reality games. It was launched in 2005 and it is programmed in C++ and C#.

A lot of developers find it easier to use because of its functionality, ease of coding and the ability to be used for any sort of game.

Since it is also a cross-platform engine, it is supported by Windows as well as macOS and can run on consoles like Playstation and Xbox.

Some of the famous game titles made by using Unity engine are:

  1. Temple Run.
  2. Assassin’s Creed Identity.
  3. Deus Ex: The Fall.

2. Unreal

unreal_engine

Unreal is a game engine developed by Epic Games which was first showcased in 1998 in the first-person shooter game Unreal. Developers love working on it because its code is written in C++and ease of use it offers.

Its latest version Unreal 4, is said to be the easiest engine to use as it creates very good graphics. Just like Unity it is a cross-platform engine and supports consoles like Playstation, Nintendo, and Xbox.

Some of the famous game titles created by using the Unreal engine are:

  1. Unreal Tournament 2004.
  2. Deus Ex.
  3. Fortnite.
  4. Batman: Arkham City.
  5. Life is Strange.
  6. Gears of War.

3. CryEngine

cryengine

CryEngine is a game engine developed by German developer Crytek. It has been used in all of their titles. It has also been used for many third-party games under Crytek’s licensing scheme and has beautiful graphics. Along with it, the characters made with it are life-like.

To learn how to use CryEngine, there are a lot of free resources. Since it is programmed in C++, C#, and Lua, it is easy to code and supports platforms like macOS and Windows and consoles like Playstation and Xbox.

Some of the famous game titles developed on CryEngine are:

  1. FarCry.
  2. Crysis.
  3. Warface.
  4. Sniper 3.

Conclusion

We tried compiling the best list for the top game engines in game development and most of them provide more or less the same gaming experience. What you like will completely depend on your experience you had while playing the game designed on that engine.

Keep playing and keep developing !!

Categories
Backend Developer

How to Integrate dotenv with NestJS and TypeORM

Dotenv integration with NestJS and TypeORM.

While using third party sources in application development, there must be some involvement of SSH keys or API credentials. This becomes a problem when a project is handled by a team of developers. Thus, the source code has to be pushed to git repositories periodically. Once the code is pushed to a repository, anyone can see it with the third-party keys.

A very prominent and widely used solution for this problem is using environment variables. These are the local variables containing some useful information like API keys and are made available to the application or project.

A tool known as dotenv has made it easy to create such variables and making these variables available to the application. It is an easy to use tool which can be added to your project by using any package manager.

We will use yarn as a package manager.

First, add the package using terminal.


yarn add dotenv

Since we are using NestJS which is based on typescript, so we need to add the “@types” package for the same that acts as an interface between javascript and typescript package.


yarn add @types/dotenv

Since the database to be used is Postgres, so install the necessary driver for Postgres.


yarn add pg

Now install the TypeORM module to your nest project.


yarn add @nestjs/typeorm typeorm

Now, create TypeORM entities in your project folder- For this illustration, we will be creating a folder ‘db‘ inside the ‘src‘ folder of our nest project and inside this folder, create another folder ‘entities‘ and create a typescript file containing information about your TypeORM entity.

For the sake of simplicity, we will create a user-entity file. Also, we will be creating an ‘id‘ field, a ‘name‘ field and an ‘email‘ field for this entity.

#src/db/entities/user.entity.ts

import { BaseEntity, Column, Entity, PrimaryGeneratedColumn } from 'typeorm';

@Entity({name: 'UserTable'})
class UserEntity extends BaseEntity {

  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  name: string;

  @Column()
  email: string;
}

export default UserEntity;

Note that this entity is given the name ‘UserTable’ which is optional but in case of migration it becomes somewhat useful. We will get to know the reason shortly.

Now create a migration file for this user entity. Migration file can be created using a command-line interface with the following command:


typeorm migration:create -n CreateUserTable

This will create a migration file with the timestamp as a substring in the name of this file.

Here, ‘CreateUserTable‘ will be the name of your migration file created by the TypeORM environment. Now we will create a folder ‘migrations’ inside the ‘db’ folder and place the migration file inside it if it is not done already.

Now create a separate file that will be used as a migration utility to decide the schema of the database. Thus, we can name this file as migrationUtil.ts

Inside this migration util file, create functions to get various types of columns namely-varchar, integer etc.

We will be creating two functions for illustration, namely ‘getIDColumn‘ and ‘getVarCharColumn‘.

#src/util/migrationUtil.ts

import { TableColumnOptions } from 'typeorm/schema-builder/options/TableColumnOptions';

class MigrationUtil {

  public static getIDColumn(): TableColumnOptions[] {
    const columns: TableColumnOptions[] = [];
    columns.push({
      name: 'userId',
      type: 'int',
      isPrimary: true,
      isNullable: false,
      isGenerated: true,
      generationStrategy: 'increment',
    });

    return columns;
  }

  public static getVarCharColumn({ name, length = '255', isPrimary = false, isNullable = false, isUnique = false, defaultValue = null }): TableColumnOptions {
    return {
      name,
      length,
      isPrimary,
      isNullable,
      isUnique,
      default: `'${defaultValue}'`,
      type: 'varchar',
    };
  }
}

export default MigrationUtil;

Here, ‘TableColumnOptions’ is a type provided by typeorm out of the box.

The code for this file is pretty straight whenever each of these functions are called, they create a separate column in your entity table.

Now, back to the ‘CreateUserTable’ migration file, the file should look like this:

#src/db/migrations/1578306918674-CreateUserTable.ts

import { MigrationInterface, QueryRunner, Table } from 'typeorm';

export class CreateUserTable1578306918674 implements MigrationInterface {

    public async up(queryRunner: QueryRunner): Promise<any> {
        
    }

    public async down(queryRunner: QueryRunner): Promise<any> {
        
    }

}

Now, add a table to this migration file using our migration utility file as:

#src/db/migrations/1578306918674-CreateUserTable.ts

....
private static readonly table = new Table({
        name: 'UserTable',
        columns: [
          ...MigrationUtil.getIDColumn(),
          MigrationUtil.getVarCharColumn({name: 'name'}),
          MigrationUtil.getVarCharColumn({name: 'email'}),
        ],
    });

....

Note that the name of this table is given same as the userEntity so as to improve entity-table mapping for developers. Also, finish up the code for async ‘up’ and ‘down’ methods using QueryRunner.

The idea is to create three columns in the user table – ‘userId’, ‘name’ and ’email’.

Thus, in the end, the migration file will be looking something like this:

#src/db/migrations/1578306918674-CreateUserTable.ts

import { MigrationInterface, QueryRunner, Table } from 'typeorm';
import MigrationUtil from '../../util/migrationUtil';

export class CreateUserTable1578306918674 implements MigrationInterface {

    private static readonly table = new Table({
        name: 'UserTable',
        columns: [
          ...MigrationUtil.getIDColumn(),
          MigrationUtil.getVarCharColumn({name: 'name'}),
          MigrationUtil.getVarCharColumn({name: 'email'}),
        ],
    });

    public async up(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.createTable(CreateUserTable1578306918674.table);
    }

    public async down(queryRunner: QueryRunner): Promise<any> {
        await queryRunner.dropTable(CreateUserTable1578306918674.table);
    }

}

Now, create your environment files containing environment variables. We will be creating two .env files, namely- development.env and test.env.

The environment variables for development.env will be:

#env/development.env

TYPEORM_CONNECTION = postgres
TYPEORM_HOST = 127.0.0.1
TYPEORM_USERNAME = root
TYPEORM_PASSWORD = root
TYPEORM_DATABASE = dotenv
TYPEORM_PORT = 5432
TYPEORM_ENTITIES = db/entities/*.entity{.ts,.js}
TYPEORM_MIGRATIONS = db/migrations/*{.ts,.js}
TYPEORM_MIGRATIONS_RUN = src/db/migrations
TYPEORM_MIGRATIONS_DIR = src/db/migrations
HTTP_PORT = 3001

And the environment variables for test.env will be:

#env/test.env

TYPEORM_CONNECTION = postgres
TYPEORM_HOST = 127.0.0.1
TYPEORM_USERNAME = root
TYPEORM_PASSWORD = root
TYPEORM_DATABASE = dotenv-test
TYPEORM_PORT = 5432
TYPEORM_ENTITIES = db/entities/*.entity{.ts,.js}
TYPEORM_MIGRATIONS = db/migrations/*{.ts,.js}
TYPEORM_MIGRATIONS_RUN = src/db/migrations
TYPEORM_ENTITIES_DIR = src/db/entities
HTTP_PORT = 3001

Now, create a TypeORM config file for the connection setup.

We will place this file in the ‘config‘ folder under ‘src‘ folder of the project.

#src/config/database.config.ts

import * as path from 'path';

const baseDir = path.join(__dirname, '../');
const entitiesPath = `${baseDir}${process.env.TYPEORM_ENTITIES}`;
const migrationPath = `${baseDir}${process.env.TYPEORM_MIGRATIONS}`;

export default {
  type: process.env.TYPEORM_CONNECTION,
  host: process.env.TYPEORM_HOST,
  username: process.env.TYPEORM_USERNAME,
  password: process.env.TYPEORM_PASSWORD,
  database: process.env.TYPEORM_DATABASE,
  port: Number.parseInt(process.env.TYPEORM_PORT, 10),
  entities: [entitiesPath],
  migrations: [migrationPath],
  migrationsRun: process.env.TYPEORM_MIGRATIONS_RUN === 'true',
  seeds: [`src/db/seeds/*.seed.ts`],
  cli: {
    migrationsDir: 'src/db/migrations',
    entitiesDir: 'src/db/entities',
  },
};

Here, process.env will contain all our environment variables.

Note that the environment will be specified by us during command execution and thus, anyone of the files ‘development.env’ or ‘test.env’ will be taken as environment variables supplying file.

In the same folder, create another configuration file for dotenv and we will name it as ‘dotenv-options.ts’.

#src/config/dotenv-options.ts

import * as path from 'path';

const env = process.env.NODE_ENV || 'development';
const p = path.join(process.cwd(), `env/${env}.env`);
console.log(`Loading environment from ${p}`);
const dotEnvOptions = {
  path: p,
};

export { dotEnvOptions };

The code for this file is pretty straight.

Note that the line of code containing console.log call will let us know which environment is taken by the nest while executing commands and the same file is being provided as dotenv options below it.

Now, to successfully integrate dotenv with nest, it is recommended by official nest docs to create a config service along with a config module.

Thus, create a ‘services’ folder and inside that folder- create a ‘config.service.ts’ file.

#src/Services/config.service.ts

import * as dotenv from 'dotenv';
import * as fs from 'fs';
import * as Joi from '@hapi/joi';
import { Injectable } from '@nestjs/common';
import IEnvConfigInterface from '../interfaces/env-config.interface';
import { TypeOrmModuleOptions } from '@nestjs/typeorm';
import * as path from 'path';

@Injectable()
class ConfigService {
  private readonly envConfig: IEnvConfigInterface;

  constructor(filePath: string) {
    const config = dotenv.parse(fs.readFileSync(filePath));
    this.envConfig = this.validateInput(config);
  }

  public getTypeORMConfig(): TypeOrmModuleOptions {
    const baseDir = path.join(__dirname, '../');
    const entitiesPath = `${baseDir}${this.envConfig.TYPEORM_ENTITIES}`;
    const migrationPath = `${baseDir}${this.envConfig.TYPEORM_MIGRATIONS}`;
    const type: any = this.envConfig.TYPEORM_CONNECTION;
    return {
      type,
      host: this.envConfig.TYPEORM_HOST,
      username: this.envConfig.TYPEORM_USERNAME,
      password: this.envConfig.TYPEORM_PASSWORD,
      database: this.envConfig.TYPEORM_DATABASE,
      port: Number.parseInt(this.envConfig.TYPEORM_PORT, 10),
      logging: false,
      entities: [entitiesPath],
      migrations: [migrationPath],
      migrationsRun: this.envConfig.TYPEORM_MIGRATIONS_RUN === 'true',
      cli: {
        migrationsDir: 'src/db/migrations',
        entitiesDir: 'src/db/entities',
      },
    };
  }

  /*
	  Ensures all needed variables are set, and returns the validated JavaScript object
	  including the applied default values.
  */
  private validateInput(envConfig: IEnvConfigInterface): IEnvConfigInterface {
    const envVarsSchema: Joi.ObjectSchema = Joi.object({
      NODE_ENV: Joi.string()
        .valid('development', 'test')
        .default('development'),
      HTTP_PORT: Joi.number().required(),
    }).unknown(true);

    const { error, value: validatedEnvConfig } = envVarsSchema.validate(
      envConfig,
    );
    if (error) {
      throw new Error(`Config validation error: ${error.message}`);
    }
    return validatedEnvConfig;
  }
}

export default ConfigService;

Here, ‘IEnvConfigInterface‘ is an interface provided explicitly by us to improve the understandability of code.


export default interface IEnvConfigInterface {
  [key: string]: string;
}

The dotenv.parse will read the contents of the file containing environment variables and is made available for use. It can accept string or buffer and convert it into an object of key-value pairs.

This object is then validated by using Joi schema object which is a library provided by hapi. Under this schema, we have specified that the environment (whether test or development) will be grabbed as the NODE_ENV key in the command line.

Also, if no environment is specified, then set the environment to ‘development’. Thus, our envConfig variable is now initialized with this validated object.

Now, create a configModule and import it to app module.

#src/modules/config.module.ts

import { Global, Module } from '@nestjs/common';
import ConfigService from './Services/config.service';

@Global()
@Module({
  providers: [
    {
      provide: ConfigService,
      useValue: new ConfigService(`env/${process.env.NODE_ENV || 'development'}.env`),
    },
  ],
  exports: [ConfigService],
})
export default class ConfigModule {
}

Here config service is injected into this module. But since our config service is expecting an argument through the constructor, we will use ‘useValue’ to provide this service an argument which by default is development.env file, if no environment is explicitly provided during execution of cli commands.

Now we will create another loader file that will load all the configurations for database and dotenv.

We will create this file in ‘cli’ folder under ‘src’ folder of our project and name it as ‘loader.ts’.


import * as dotenv from 'dotenv';
import { dotEnvOptions } from '../config/dotenv-options';

// Make sure dbConfig is imported only after dotenv.config

dotenv.config(dotEnvOptions);
import * as dbConfig from '../config/database.config';

module.exports = dbConfig.default;

Note that there is a comment in the code to import dbConfig only after dotenv config is imported. This is because our database configuration will depend on the environment used by nest.

Now in our package.json file under the ‘scripts’ section, we will add two key-value pairs that will be our cli command for migration.

...

"migrate:all": "ts-node ./node_modules/typeorm/cli migration:run -f src/cli/loader.ts",
"migrate:undo": "ts-node ./node_modules/typeorm/cli migration:revert -f src/cli/loader.ts"

...

Note that this command will directly execute our loader file.

And, that’s it!

We have successfully integrated dotenv with NestJS and TypeORM.

To test this, start your database server, and then run the following cli commands one after another:


NODE_ENV=development yarn migrate:all
NODE_ENV=test yarn migrate:all

It will console the environment currently being used by us, which can be seen below:

Frequently Asked Questions

Categories
Javascript

Top FrontEnd JS Framework to learn in 2020

2019 can be described as the revolutionary year for JavaScript frameworks, as we saw huge development of these frameworks and the beginning of their use among the masses.

Read more to keep yourself updated with the frameworks that are predicted to rise.

What is JavaScript Framework?

JavaScript is a programming language that is commonly used for the development of moderate applications. It is lightweight and supported by the majority of the browsers we use in our daily life. It supports both Object-Oriented programming(OOPs) and Procedural programming. Hence, it is used commonly for making web pages with the client-side script to interact with the user and make the web pages effective and concise.

Framework

It is nothing but a large part of a code that you can apply to your code to some problem that you are facing in a specific domain. It can be used by providing “callbacks“.

Advantages of JavaScript Frameworks

  • It has strong community support which keeps it always updated.
  • Possess extensions that help in debugging components.
  • Plenty of third party component support.
  • The efficiency of the code increases.
  • It is free and open to use for all.
  • Possesses the ability to keep the user interface in synchronization with the state of the system.

2019 being such a great year for JS, what does 2020 have in store for us??

Now that we have discussed the JavaScript Frameworks, let us check out the rising frameworks in 2020:

1.Angular

Angular

Angular is an open-source application framework, which works on TypeScript. It has been developed and maintained by Google and released back in 2016 when there weren’t many framework applications. Due to this, it was the most widely used software back then. To date, it has 6 versions- Version 2, version 4, Version 5, Version 6, Version 7, Version 8. Although its position has decreased because of the launch of new frameworks, it is still one of the top 3 most widely used frameworks around the world and companies prefer to hire people who have the knowledge of Angular,

Advantage

  • Very reliable due to the support from Google.
  • A large number of tools for performing actions.
  • The quality of programming is high.
  • Good quality code generation.

Disadvantage

  • It requires a lot of knowledge about the software before working on it.
  • It consumes a large amount of energy.
  • Poor optimization of problem-solving, leading to low productivity.

2.React

React

The current leader of all the framework fields, React is developed by Facebook developers. It was launched completely in November last year while a prototype was launched back in 2013. It is based on reusable components. Most of the companies use it as their primary framework tool. It was the fastest-growing application in the framework field last year and is supposed to maintain that growth in 2020 too. Most of the developers speak in the same voice that React is easy to learn given that you have basic knowledge of JavaScript.

Advantage

  • Highly Adjustable.
  • Files composed are of small size.
  • Has a good JavaScript library.
  • Good stability.

Disadvantage

  • Documentation is not very fluent.
  • Proper study is required to use the extra tools to use them for coding.

3.Vue

Vue

Vue is an Open-source JavaScript-based framework that is mostly used for building software interface for the users. It was released in February 2014. Its creator, Evan You, worked for Google and used Angular. He noticed how heavy the framework was and when he created Vue, he made sure that it would be lighter than Angular. At 20KB in size, it has the smallest size among all frameworks. Due to this, it is rapidly growing but it still has a long way to the top.

Advantage

  • Fast Installation.
  • Ridiculously small size.
  • The study of components before coding is not required.
  • Simple to use.
  • It offers a lot of extensions to code with.
  • Blends with other programming languages without any problem.

Disadvantage

  • A small community of users and developers.
  • Less amount of tools.
  • Highly fluctuating.

4.Meteor

Meteor

Meteor is a free and open-source Framework based in JavaScript written in Node. It has the ability to produce cross-platform code among different platforms. It was released in 2012 and had a good growth rate but its growth was stalled by frameworks like Angular and React.

Advantage

  • Generates Cross-Platform code.
  • Easy to use.

Disadvantage

  • Lack of user and developer community.

5.Svelte JavaScript

Svelte Javascript

Svelte is a framework that is used for creating code. Its main developer is Richard Harris. Due to its small size, its speed gets increased many folds.

Advantage

  • Small Size.
  • Fast speed of operation.
  • It can exist separately with the code which was created by it.
  • Easy to use.
  • It requires less amount of memory.

Disadvantage

  • Very small community.
  • Limited functions and tools.

6.Ionic

Ionic

Ionic framework is a complete open-source Software Development Kit (SDK) for hybrid mobile development created by Max Spiery, Ben Sperry, and Adam Bradley of Drifty Co. in 2013. The pilot version was built on AngularJS and Apache Cordova. However, the latest release was re-built as a set of Web Components

Advantage

  • It is supported by all the platforms.
  • It allows the user to build applications.
  • Big companies like PayPal use it.
  • The Ionic framework provides a command-line interface (CLI) to create projects.

Disadvantage

  • This framework requires time to learn it.
  • It is a little complex compared to other frameworks.
  • It is not very secure when compared to other frameworks.
  • Specific plugins have to be developed.

7.Ember

ember

Ember is an open-source JavaScript Framework based on Model-view-view-Model (MVVM). It is used by websites like Apple, Twitch, Groupon, and Linkedin. It is owned by Tilde Incorporated and was launched in 2011

Advantage

  • It contains built-in testing tools.
  • Good community support from users and developers.
  • It is capable of giving high performance.
  • Its performance is good

Disadvantage

  • It requires a lot of study for doing coding on it.
  • Even after a large community, development speed is slow.

Conclusion

The frameworks mentioned above are the ones to be watched for the year 2020. But that does not mean the other frameworks are bad. It just means that they require a few modifications in their setup. Who knows they might be the one to watch out next year. But out of the frameworks mentioned, the ones to be observed with a close eye would be Angular, React and Vue.

Categories
Javascript

Javascript Frameworks you should definitely learn in 2020

Javascript has come out to be one of the most prominent languages for the past few years, especially after the rise of NodeJS. Since Javascript is the only language supported by browsers, there is no denying the fact that web development needs expertise in Javascript.

And with Javascript being supported in the backend, this came as a huge benefit as a single function/library/utility, which can be shared across both frontend and backend. Hence development time and resources are reduced.

With an increase in the use of javascript, many people are opting in to use javascript and the language is evolving faster and bringing the best of all the world. Be it Typescript, Promises, async awaits, these features come in very handy when doing enterprise development.

Backend Frameworks of Javascript you should learn in 2020

Express, or NestJS (Typescript)

Expressjs

Express JS is the de-facto for the NodeJS, a web application framework built by  TJ Holowaychuk. NestJS is the wrapper on top of the express js which has multiple other plugins that come handy when doing an enterprise-level project. And not to forget that NestJS come out of the box with typescript support and Dependency injections.

The framework structure is very similar to that of angular 2+, so in case you know either of one, the other one would be really fast to grab.

A big difference is that though Nest js use express under the hood, express is a callback-based framework, whereas nest mostly use promises and async-await, so codes are pretty neat.

So, if you are going to do an MVP and need to move really fast and stick to just plain es6 or es7, I would recommend sticking to Express. But if you can give more time and compatibility with typescript, I would strongly recommend using nestjs, as it comes with ‘out-of-the-box’ multiple supported integrations.

Here is a quick demo on how you can use nestjs with typeorm ( ORM for SQL Database connections). And you can clone the same codebase and remove the parts which you are not going to use.

TypeORM

typeorm

The database is a very crucial part of almost any web or backend development. Writing queries and managing connections become really a nightmare as the project scales, and if there is any need for changing database servers, it means you have to go through all the queries and connection handling. To avoid such things and keep the code really clean, we use the ORM layer.

The two major ORMs for Node are Sequelize and TypeORM.

TypeORM support typescript out of the box and comes with both Datamapper and ActiveRecord support out of the box.


Though typeORM is very new, has an active development and still, in alpha production, it is yet quite stable and can be used for enterprise-level projects.

NestJS come out pretty handy when integrating TypeORM as if they are meant to go side by side. I won’t be surprised if NestJS start using TypeORM as its default ORM Layer.

Here is a quick tutorial on how you can use TypeORM with One-to-one, one-to-many, many-to-many relationships with any SQL server using NestJS.

GraphQL, Apollo Server

GraphQL

GraphQL was developed at Facebook and is being used intensively for data-driven web apps. Though many backend languages and framework support graphql, to date only NodeJS has the best integration with the apollo server.

So, if you are going to do GraphQL web development, Nodejs is generally the first preference for development for the backend.

NestJS provides a pretty clean GrapQL plugin, that can be integrated and can use to start development.


Though GraphQL is generally preferred to be used over the No-SQL database, it’s not that it is meant to be done by No-SQL only. But it can do pretty well with SQL servers and TypeORM on top of it.

Though in some cases you might need to integrate the DataLoader for optimization of queries and take that extra relational feature of the SQL server.

Here is q quick tutorial on how you can use GraphQL with NestJS and Typeorm and Dataloader

If you know the above three frameworks, you can do almost any kind of web or backend development

Frontend Frameworks of Javascript you should learn in 2020

Front_end frameworkds

React Native for Web

There is no denying the fact that React & React-native have been in major use, but with flutter pushing flutter web and to write single code for the native as well as web apps, there is a definitive need for a similar framework which does the same.

Thanks to Necolas for starting this project, which has around 15.5k stars on Github. Though this framework is not widely used it’s going to be a breakthrough in 2020, where you can just maintain a single codebase for all your mobile and web apps.

If you already know React or React-Native, then React Native web is just a morning coffee for you, and you can directly start building apps by using its documentation.


Here you can read a brief introduction of the react-native web.

You might have to struggle a bit with some libraries, but it’s not a deal-breaker. You can read more about a happy struggle with react native web

If you know Expo and have been doing react native development on top of Expo, you can follow the guide here, Does expo support react native web

Here is a quick comparison guide on react native web vs react

React, React-native ( NextJs for server-side rendering)

React & React native still rule the web and app development. You can read the related topics here

Why learning react native makes sense in 2020

Angular

angular

If you want to build an enterprise-level project, I would recommend going for Angular. And, the main reason angular still is the first preference for enterprise or a huge project is that it comes with a lot of juices out of the box.

The first and foremost is the support for typescript out of the box. It also supports dependency injection and the framework is very well-enabled with guards, services, interceptors, middleware that can be directly plugged in and can be taken advantage of.

You can read in details about the difference between angular and react here

If you noticed above, we have recommended NestJs as a backend framework. If you know NestJS, then the good news is NestJS is actually inspired by Angular, so if you know one of these, learning the other would be really fast and nice.

If you are looking to get started with angular, here is a quick guide on Guide To Your First Angular 5 App

Frequently Asked Questions

Categories
API Backend Developer Node

Top 10 NodeJS Frameworks For Developers in 2020

Node.js is an open-source, cross-platform runtime environment built on Chrome’s V8 javascript engine. The event-driven, non-blocking I/O model makes the NodeJS framework an extremely lightweight and efficient web application.

As a developer, one gets to smoothly use the same language for both clientside and serverside scripting and this unique facility has increased the quick adoption of NodeJS frameworks by many developers across the globe in building web applications of any size.

Since it’s been launched in 2009 as a tool for building scalable, server-side web applications it has brought about exponential growth in its usage.

In addition, Node facilitates quick prototyping in building unique projects.

Let’s check out this list of 10 Top NodeJS Frameworks:

Hapi.JS

Hapi is a powerful and robust framework that is used for developing APIs. The well-developed plugin system and various key features such as input validation, configuration-based functionality, implement caching, error handling, logging, etc. make the Hapi one of the most preferred frameworks. It is used for building useful applications and providing technology solutions by several large-scale websites such as PayPal, Disney.

Hapi
Hapi builds secure, powerful, scalable applications with minimal overhead and out-of-box functionality

Hapi is a configuration-driven pattern, traditionally modeled to control web server operations. A unique feature it has is the ability to create a server on a specific IP, with features like the ‘onPreHandler’, we can do something with a request before it is completed by intercepting it and doing some pre-processing on the request.

Express.JS

Express.js was built by TJ Holowaychuk, one of the members of the core Node project team. A large community backs this framework, so it has the advantages of continuous updates and reforms of all the core features. This is a minimalist framework that is used to build a number of mobile applications and APIs.

Express
Express is a minimal and flexible Node.JS web application framework providing a robust set of features

It’s robust API allows users to configure routes to send/receive requests between the front-end and the database (acting as a HTTP server framework).

A good advantage with express is how it supports a lot of other packages and other template engines such as Pug, Mustache, EJS and a lot more.

Socket.io

Socket
Socket the fastest and reliable real-time engine

It is used for building real-time web applications. It’s a Javascript library that allows the bidirectional data flow between the web client and server. Asynchronous data I/O, binary streaming, instant messaging are some of the most important features of this framework.

Total.JS

Total.js is a modern and modular NodeJS supporting the MVC architecture. Angular.js, Polymer, Backbone.js, Bootstrap and other clientside frameworks are fully compatible with this framework. This framework is totally extensible and asynchronous. The fact that it does not require any tools such as Grunt to compress makes it easy to use. It also has NoSql embedded in it and supports array and other prototypes.

Total
For fast, furious and powerful websites, REST services, real-time applications TotalJS is the best choice

Total.js has some really beautiful versions like the Total.js Eshop, which contains a user interface optimized for mobile devices, and it is downloadable by all premium members. Eshop is one of the best Node.js e-commerce system. This is because of its many versions of unique content management system(CMS).

Sail.JS

This MVC framework has become very popular with NodeJS developers and this framework has gained traction through the development of chat applications, dashboards and multiplayer games. It is most famous for building data-driven APIs. It uses waterline for object-related mapping and db solutions. This framework uses Express.js for handling HTTP requests and is built upon Node.js.

Sail
Sail


Its compatibility with Grunt modules, including LESS, SASS, Stylus, CoffeeScript, Jade, Dust makes it an ideal candidate for browser-based applications.

Sail is highly compatible with several front-end platforms. Developers have enough freedom to their development while implementing this framework.

Derby

Derby
Derby is a full-stack framework for writing modern web applications

This is an MVC framework that is used for creating real-time mobile and web applications. Derby’s Racer, a real-time data synchronization engine for Node.js allows multi-site, real-time concurrency and data synchronization across clients and servers. The racer optimizes conflict resolution and allows real-time editing of the application by leveraging the ShareJS.

Derby is an open-source framework based on MVC structure and it is a full-stack NodeJS web framework. Derby is considered ideal for developing real-time collective applications. Using DerbyJS , developers can easily add customized codes and build real-time and effective custom made websites.

Meteor.JS

One of the fundamentally most used NodeJS frameworks is Meteor.JS. And this list would remain incomplete if we didn’t mention the MeteorJS framework. This is a full-stack framework of NodeJS which allows users to build real-time applications.

Meteor
Meteor

It is used to create both mobile and web-based javascript applications.

Backed by a huge community of developers, tutorials, custom packages and documentation, this framework is used to create some great web and mobile applications for only Javascript only.

Loopback

Loopback is a highly-extensible API framework that allows the user to create such APIs that can work with any kind of web client and can be easily bridged to backend sources. This new age modern application comes with complex integration. With Loopback being an open-source framework, the user can create dynamic REST APIs with a minimum or no knowledge of coding.

Loopback
Highly extensible NodeJS framework for building APIs and microservices

Loopback permits developers to create SDKs and API documentation. This is possible due to widget-API explorer that comes in default with loopback.

Also, it comes with model-relation-support, third party login and storage service, API swagger, better user management policy

Koa

Koa was created by the same team that created Express.js and it is often referred to as the next-generation NodeJS framework. Koa is unique in the fact that it uses some really cool ECMAScript(ES6) methods that have not even landed in some browsers yet. It allows you to work without callbacks while providing you with an immense increase in error handling.

It requires a NodeJS version of at least 0.11 or higher.

Koa
Next-generation web framework for NodeJS

KoaJS supports syn/await keywords and helps to manage the codes neatly.

Also, it doesn’t pack any bundle of middleware in the core. That makes server writing with Koa faster and enjoyable. KoaJS comes with more options for customization. It allows you to work with applications from scratch where developers can add those features only which they need.

NestJS

NestJs is a framework built with Node.js, It is used for building efficient, scalable Node.js server-side applications. Nest uses progressive JavaScript and is written with TypeScript. Being built with TypeScript means that Nest comes with strong typing and combines elements of OOP(Object Oriented Programming), FP(Functional Programming) and FRP(Functional Reactive Programming).

NestJS
NestJS Framework- a progressive NodeJS Framework for building efficient, reliable and scalable server-side applications


Advantages of NodeJS Framework

NodeJS Framework is now emerging as the most commonly used development framework for building frontend and backend for web applications. And it is the most preferred environment for custom web development. Let’s check some of the major advantages of NodeJS Framework:

  • Real-time working environment
  • Simple coding experience
  • Seamless data streaming
  • Same code pattern throughout development
  • User-friendly

Final Analysis

After going through this article, we can certainly understand that the adoption of a particular framework depends totally upon the kind of website and web application we are planning to build. The list is endless but we tried presenting 10 most useful NodeJS Frameworks for you depending on utilization and ubiquity in the javascript community

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.