Wednesday, August 7, 2019

How To Hide iPhone or iPad Keyboard When Tapping On The Screen?

To hide or dismiss the keyboard on iPad or iPhone safari browser, you need to lose the focus on your input.
document.activeElement.blur();
With this line you remove the focus and the keyboard disappear.

To be able to hide or dismiss iPhone or iPad keyboard when tapping on the screen, you need to add event on your body. It is possible to recognize touch events on the iPad's Safari browser using jQuery. If you're using jQuery 1.7+ it's even simpler to fix the problem as follows:
$(document).ready(function () {
    $('body').on({
      touchstart: function() {
        if (document.activeElement) {
          document.activeElement.blur();
        }
      }
    });
 });
This detects when you tab the body and then blurs it, so the keyboard will disappear.

Friday, June 28, 2019

How To Scroll To The Top of The Page in React and Typescript?

Issue:
When navigating into another page, its position will remain same like the previous page but you want to scroll to the top of new routed/rendered page.

Solution
I usually put an empty div on top of that page, and gave it a ref, so that, later I can use the scrollIntoView() method to scroll the page into that div.

In TypeScript, you'll have more extra steps to do so, seems to be annoying, but it's actually very helpful because you can take advantages of the type system. First, define a ref like this:
class YourComponent extends React.Component {
  private scrollAnchorRef: any;

  //or private scrollAnchorRef: RefObject<HTMLElement>

  constructor(props) {
    super(props);
    this.scrollAnchorRef = React.createRef(); // Create a ref object 
  }

  render() {
    <div ref={this.scrollAnchorRef}>
      ...
    </div>
  }
}

I have used any type instead of a generic HTMLElement type (recommended) when defining a ref, because it will help the compiler narrow down the type so you'll have better suggestion in the next step.

Now, when you finish rendering/loading page and want to scroll to the top of element, you can do:
  this.scrollAnchorRef.current.scrollIntoView({ block: 'start', behavior: 'smooth' })
And you'll get an error message says: TS2531: Object is possibly 'null'

The reason is, RefObject.current has the type of T | null, because React will actually set an element's ref into null when it re-render, and if you're trying to scroll during re-render, you'll run into problems.

The solution is simple, add an existent check:
 const anchor = this.scrollAnchorRef;
 if (anchor) {
   anchor.current.scrollIntoView({ block: 'start', behavior: 'smooth' }); 
}
Here is the complete solution.

class YourComponent extends React.Component {
  private scrollAnchorRef: any;

  constructor(props) {
    super(props);
    this.scrollAnchorRef = React.createRef(); // Create a ref object 
  }

  componentDidUpdate(prevProps) {
    if (this.props.location !== prevProps.location) {
      const anchor = this.scrollAnchorRef;
     if (anchor) {
        anchor.current.scrollIntoView({ block: 'start', behavior: 'smooth' }); 
     }
    }
  }

  render() {
   <div ref={this.scrollAnchorRef}>
      ...
   </div>
  }
}

This is how type saved your butt when you work with React and Typescript.

Reference: React, TypeScript and scrollInToView

Monday, May 13, 2019

What Is withRouter And How And When To Use It?

withRouter
You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will pass updated match, location, and history props to the wrapped component whenever it renders.

Usage of withRouter
If you want that your component will receive Router Props, but don't want to wrap it in <Route component={Some} />. You can just use withRouter function to connect component to the Router, without additional manipulations or jsx tags wrapping. You can just export default withRouter(component)

Explanation/Example
When you include a main page component in your app, it is often wrapped in a component like this:
 <Route path="/movies" component={MoviesIndex} />
By doing this, the MoviesIndex component has access to this.props.history so it can redirect the user with this.props.history.push

Some components (commonly a header component) appear on every page, so are not wrapped in a :
 render() {
   return (<Header />);
 }
This means the header cannot redirect the user.

To get around this problem, the Header component can be wrapped in a withRouter function when it is exported as below:
 export default withRouter(Header)
This gives the Header component access to this.props.history, which means the header can now redirect the user.

Refs: REACT TRAINING / REACT ROUTER / withRouter

Thursday, April 4, 2019

How To Sort Array By Name Or Date In Javascript?

Suppose you have an array users. You need to sort the array by name or date.
var users = [
  {id: 1, firstName: 'Anup', created_date: Mar 12 2012 10:00:00 AM}, 
  {id: 2, firstName: 'Tom', created_date: Mar 8 2012 08:00:00 AM}
];
To sort the array of objects by created_date
Turn your strings into dates, and then subtract them to get a value that is either negative, positive, or zero.
Example:
 users.sort((a, b) => new Date(b.created_date) - new Date(a.created_date));   
To sort the array of objects by firstName
Suppose you have an array users. You may use users.sort and pass a function that takes two arguments and compare them (comparator).
It should return
• something negative if first argument is less than second (should be placed before the second in resulting array)
• something positive if first argument is greater (should be placed after second one)
• 0 if those two elements are equal.

In our case if two elements are a and b, we want to compare a.firstname and b.firstname. When sorting strings toLowerCase() is very important - capital letters could affect your sort.
Example:
users.sort((a, b) => a.firstName.toLowerCase() !== b.firstName.toLowerCase() ? a.firstName.toLowerCase() < b.firstName.toLowerCase() ? -1 : 1 : 0);
If compared strings contain unicode characters you can use localeCompare function of String class like the following:
users.sort((a, b) => a.firstname.toLowerCase().localeCompare(b.firstname.toLowerCase()));

Monday, April 1, 2019

How To Solve Mongo - couldn't connect to server 127.0.0.1:27017 error?

Problem:
[js] Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused :
connect@src/mongo/shell/mongo.js:257:13
@(connect):1:6

Solution
Normally this caused because you didn't start mongod process before you try starting mongo shell.

Start mongod server
 mongod
Open another terminal window and start mongo shell
 mongo

Tuesday, March 19, 2019

What Is Difference Between Dot Notation And Bracket Notation?

Accessing Properties on an Javascript Object
There are two ways to work/access properties(key/value pair) on a Javascript object:
• Dot Notation
• Bracket Notation

Dot Notation
Dot notation is used most frequently. Let's first look at Dot notation. Consider this example below:
let person = {
  name: 'Anup',
  age: 34
};
Here is a person object with 2 properties name and age. Let's say we need to change the name of the person, so we need to access the name property of an object Person. We can use dot notation as below
 person.name = 'John';
 console.log(person); // {name: 'John', age: 34}

 console.log(person.name); // John
This is an example of dot notation. You can change properties on an object by specifying the name of the object, followed by a dot (period) followed by the property name person.name = 'John'. Similarly we can use the dot notation to read the value of property like person.name.

Bracket Notation
You can access properties on an object by specifying the name of the object followed by the property name in brackets.
 person['name'] = 'Doe';
 console.log(person); // {name: 'Doe', age: 34}
When working with bracket notation, property identifiers only have to be a String. They can include any characters, including spaces. Variables may also be used as long as the variable resolves to a String.

Dot Notation Vs Bracket Notation
Dot notation is bit concise, shorter and much easier to read than bracket notation and is therefor used more often.

• However, bracket notation has its own uses. Sometimes you don't know the name of the target property until the runtime. With dot notation, we can’t use dynamic variables. For example, in our user interface, user might be selecting the name of the target property dynamically.
 let selection = 'name';
 person[selection] = 'Donald';
 console.log(person); // {name: 'Donald', age: 34}
In that case, at the time of writing the code we don't know that what property we're going to access. That is going to be selected at runtime by the user so might have another variable somewhere else like selection that determines the name of the target property that the user is selecting and that can change at the runtime. We can access that property using the bracket notation in a dynamic way so we can pass selection here and we get the same result in the console.

• It is okay to use variables, spaces, and Strings that start with numbers in the bracket notation i.e. obj['1prop'], obj['prop name'] where as in dot notation, property identifiers cannot start with a number and cannot contain variables and can only be alphanumeric (and _ and $) i.e. obj.prop_1, obj.prop$.

dot notation is mostly assuming the existence of the variables if there is no intellisense while with the bracket notation there is a sense of consciousness which is good, because you really to know what you are dealing with.

• One other advantage of bracket notation. If you flatten an object so that all variables are at the root of your object but you retain the dot in the variable name to represent the properties depth you can use bracket syntax: someObject['propCollection.property']

Reference: JavaScript Quickie— Dot Notation vs. Bracket Notation

How To Make Simple Stopwatch Using Plain Javascript?

In the plain javascript you can use factory function or construction function to create an object.

Let's create a stop watch example to show how to a create a construction function. It has three methods start, stop and reset and private variables are defined as startTime, endTime, running and duration. Also it is defined readonly property called duration using Object.defineProperty method. this keyword is being used to set the properties of an object Stopwatch.
function Stopwatch() {
    let startTime = null;
    let endTime = null;
    let running = false;
    let duration = 0;

    this.start = function() {
        if (running) {
            throw new Error('Stopwatch has already started.');
        }

        running = true;

        startTime = new Date();
    };

    this.stop = function() {
        if (!running) {
            throw new Error('Stopwatch is not started yet.');
        }

        running = true;

        endTime = new Date();

        const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
        duration += seconds;

    };

    this.reset = function() {
        startTime = null;
        endTime = null;
        running = false;
        duration = 0;
    };

    //readonly property
    Object.defineProperty(this, 'duration', {
        get: function() {
            return duration;
        }
    });

}
In your browser's console log, you can run this example as below
const sw = new Stopwatch();

sw.start()
sw.stop()
sw.duration
sw.reset()

Source: Object-oriented Programming in JavaScript: Made Super Simple | Mosh | Stop watch Exercise

Monday, March 18, 2019

Four Pillars of Object Oriented Programming in Javascript

Four Pillars of Object-oriented Programming (OOP)
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism

Encapsulation
In object-oriented programming we group related variable and functions that operate on them into objects and it is called encapsulation. Let's look at the example.
let employee = {
 baseSalary: 30000,
 overtime: 10,
 rate: 20,
 getWage: function() {
   return this.baseSalary + (this.overtime * this.rate)
 }
};
employee.getWage();
We don't have any parameters in the getWage function is because all these parameters are actually modelled as properties of this object. All these properties and getWage function are highly related so they are a part of one unit (i.e employee object). In object-oriented way, your functions end up having fewer and fewer parameters. If fewer the number of parameters the easier it is to use and maintain that function so this is called encapsulation.

Encapsulation gives a couple of benefits as follows.
• Reduce Complexity - We group related variables and functions together and this way we can reduce complexity.
• Increase reusability - We can reuse these objects in different parts of a program or in different programs.

Abstraction
Think of DVD player as an object. This DVD player has a complex logic board on the inside and a few buttons on the outside that you interact with. You simply press the play button and you don't care what happens on the inside. All that complexity is hidden from you. This is abstraction in practice. We can use same technique in our objects so we can hide some of the properties and methods from the outside and this gives a couple of benefits.

• Simple Interface - We'll make the interface of those objects simpler. Understanding an object with a fewer properties and methods is easier than on object with several properties and methods.
• Reduce Complexity - With abstraction, we hide the details and the complexity and show only the essentials. This technique reduces complexity.
• Reduce or isolate the impact of change - Let's imagine that tomorrow we change inner or private methods of the object. None of these changes will leak to the outside because we don't have any code that touches these methods outside of their content object. We may delete a method or change its parameters but none of these changes will impact the rest of the applications code. So with abstraction we reduce the impact of change.

Inheritance
Inheritance is a mechanism that allows you to eliminate redundant code. Here is an example to think of HTML elements like text boxes, drop-down lists, checkboxes and so on. All these elements have a few things in common.

It should have properties like hidden and inner HTML and methods like click and focus. Instead of redefining all these properties and methods for every type of HTML elements we can define them once in a generic object. Lets called it HTML element and have other objects inherit these properties and methods.

Benefit: With inheritance we can eliminate redundant code.

Polymorphism
Poly means many and morph means form. Polymorphism means many forms. In object-oriented programming polymorphism is a technique that allows you to get rid of long if-and-else or Switch-case statements. So back to our HTML elements example, all these objects should have the ability to be rendered on a page but the way each element is rendered is different from others.

If we want to render multiple HTMl elements with object orientation, we can implement a render method in each of these objects and render method will behave differently depending on the type of the object viewer referencing. We can use one line of code like this element.render();

Benefit: With polymorphism we can refactor ugly switch case statements.
Source: Object-oriented Programming in JavaScript: Made Super Simple | Mosh Hamedani