Handling Browser Window Resize in ReactJS

| Comments

If you want to handle some use cases like “I want to update a div container width on browser window resize in react application” then you are in the right place.

In jQuery it’s fairly simple like below.

1
2
3
4
5
6
$( window ).resize(function() {
  var reelContainerWidth = $(window).width() - 400;

  // sets the width of reel-container to (window size - 400px)
  $("#reel-container").width(reelContainerWidth);
});

In the React world we have do it in slightly different way.

  1. Set initial width in default state
  2. Calculate viewport width each time the browser windows change size
  3. Re-render our component by passing the updated width through state

React way

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
var React = require("react"),
ReactDOM = require("react-dom");

var ReelContainer = React.createClass({

  getInitialState: function() {
    return {
      reelContainerWidth: 100
    };
  },

  /**
   * Calculate & Update state of new dimensions
   */
  updateDimensions() {
    const reelContainerWidth = window.innerWidth - 400;

    // sets the width of reel-container state to (window size - 400px)
    this.setState({ reelContainerWidth: reelContainerWidth });
  }

  /**
   * Add event listener
   */
  componentDidMount() {
    this.updateDimensions();
    window.addEventListener("resize", this.updateDimensions);
  }

  /**
   * Remove event listener
   */
  componentWillUnmount() {
    window.removeEventListener("resize", this.updateDimensions);
  }

  render(): React.Element {
    const reelContainerWidth = { width: this.state.reelContainerWidth };

    return(
      <div id="reel-container" style={reelContainerWidth}>
         Reel Content
      </div>
    );
  }
}

module.exports = ReelContainer;

Scope in Javascript

| Comments

Traditionally, JavaScript only has two types of scope:

1) Global Scope: Variables are known throughout the application, from the moment they are declared onwards

2) Functional Scope: Variables are known within the function they are declared in, from the moment they are declared onwards

The most recent JavaScript specs(ES6) now also allow a third scope:

3) Block Scope: Variables are known within the block they are declared in, from the moment they are declared onwards

How do I create block scope variables?

1
2
var myVariable = "Some text"; // Traditional approach
let myVariable = "Some text"; // Blocked scope

Here is some examples to understand scopes better

A globally-scoped variable

1
2
3
4
5
6
var a = 1;

// global scope
function one() {
  alert(a); // alerts '1'
}

Local scope

1
2
3
4
5
6
7
8
9
10
11
var a = 1;

function two(a) {
  alert(a); // alerts the given argument, not the global value of '1'
}

// local scope again
function three() {
  var a = 3;
  alert(a); // alerts '3'
}

Intermediate: No such thing as block scope in JavaScript (ES5; ES6 introduces let)

1
2
3
4
5
6
7
8
9
var a = 1;

function four() {
  if (true) {
    var a = 4;
  }

  alert(a); // alerts '4', not the global value of '1'
}

Global+Local: An extra complex Case

1
2
3
4
5
6
7
var x = 5;

(function () {
    console.log(x);
    var x = 10;
    console.log(x);
})();

This will print out undefined and 10 rather than 5 and 10 since JavaScript always moves variable declarations (not initializations) to the top of the scope, making the code equivalent to:

1
2
3
4
5
6
7
8
var x = 5;

(function () {
    var x;
    console.log(x); // undefined
    x = 10;
    console.log(x); // 10
})();

Intermediate: Object properties

1
2
3
4
5
6
7
var a = 1;

function five() {
  this.a = 5;
}

alert(new five().a); // alerts '5'

Advanced: Closure

1
2
3
4
5
6
7
8
9
10
11
var a = 1;

var six = (function() {
  var a = 6;

  return function() {
    // JavaScript "closure" means I have access to 'a' in here,
    // because it is defined in the function in which I was defined.
    alert(a); // alerts '6'
  };
})();

Advanced: Prototype-based scope resolution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
var a = 1;

function seven() {
  this.a = 7;
}

// [object].prototype.property loses to
// [object].property in the lookup chain. For example...

// Won't get reached, because 'a' is set in the constructor above.
seven.prototype.a = -1;

// Will get reached, even though 'b' is NOT set in the constructor.
seven.prototype.b = 8;

alert(new seven().a); // alerts '7'
alert(new seven().b); // alerts '8'

Understanding Closures in Javascript

| Comments

Closure is when a function ‘remembers’ its lexical scope even when the function is executing outside that lexical scope. ~ Kyle Simpson

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: - It has access to its own scope (variables defined between its curly brackets) - It has access to the outer function’s variables - It has access to the global variables

The inner function has access not only to the outer function’s variables, but also to the outer function’s parameters. Note that the inner function cannot call the outer function’s arguments object, however, even though it can call the outer function’s parameters directly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var pizza = function() {
  var crust = "thin";
  var toppings = 3;
  var hasBacon = true;

  var getToppings = function() {
    return toppings;
  }

  var pizzaInfo = {};
  pizzaInfo.getToppings = getToppings;

  return pizzaInfo;
}

var pizzaA = new pizza();

pizzaA.getToppings(); // returns 3
  • Closures are useful in hiding the implementation of functionality while still revealing the interface
  • Closure is one way of supporting first-class functions; it is an expression that can reference variables within its scope (when it was first declared), be assigned to a variable, be passed as an argument to a function, or be returned as a function result.
References:

Understanding Hoisting in Javascript

| Comments

“How things work?” is the question you need to ask before learning anything to master it. JavaScript is a very flexible language compared to Java, PHP, C++ and other languages, but there are unique concepts which makes the language more efficient. Understanding the concepts of Javascript helps you write better code!

Now let’s talk about Hoisting.

A variable declaration lets the system know that the variable exists while definition assigns it a value.

Variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it’s declared. This behavior is called “hoisting”, as it appears that the variable declaration is moved to the top of the function or global code.

Just remember, variable declarations and function definitions are hoisted to the top. Variable definitions are not, even if you declare and define a variable on the same line.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
function doTheThing() {
  // ReferenceError: notDeclared is not defined
  console.log(notDeclared);

  // Outputs: undefined
  console.log(definedLater);
  var definedLater;

  definedLater = 'I am defined!'
  // Outputs: 'I am defined!'
  console.log(definedLater)

  // Outputs: undefined
  console.log(definedSimulateneously);
  var definedSimulateneously = 'I am defined!'
  // Outputs: 'I am defined!'
  console.log(definedSimulateneously)

  // Outputs: 'I did it!'
  doSomethingElse();

  function doSomethingElse() {
    console.log('I did it!');
  }

  // TypeError: undefined is not a function [Because functionVar is a variable]
  functionVar();

  var functionVar = function() {
    console.log('I did it!');
  }
}

To make things easier to read

  • Declare all of your variables at the top of your function scope so it is clear which scope the variables are coming from.
  • Define your variables before you need to use them.
  • Define your functions at the bottom of your scope to keep them out of your way.

Reference: Hoisting

Reverse String Using Javascript

| Comments

There are certain ways you can reverse a string in Javascript, Some of them are effective & efficient, some of them are neat. Feel free to choose the one which fits your project needs.

1. Decrementing for-loop with concatenation

1
2
3
4
5
6
7
function reverse(s) {
  var reversedString = "";
  for(var i= s.length -1; i>=0; i--) {
    reversedString += s[i]; //reversedString = reversedString+s[i];
  }
  return reversedString;
}

The original way that I achieved the intended result was to use a decrementing for-loop that appended each character of the input to a new string in reverse order. I was able to access the parsed strings individual characters similar to the way you would reference an array’s items.

2. Incrementing/decrementing for-loop with two arrays

1
2
3
4
5
6
function reverse(s) {
  var o = [];
  for (var i = s.length - 1, j = 0; i >= 0; i--, j++)
    o[j] = s[i];
  return o.join('');
}

Another way I formed to reverse a string was to create an empty array and iterate over the length of the string with both incrementing/decrementing counters. The array position uses the incrementing counter where as the parsed in string uses the decrementing one. Finally the created array is joined into a single string and returned.

3. Incrementing for-loop with array pushing and charAt

1
2
3
4
5
6
function reverse(s) {
  var o = [];
  for (var i = 0, len = s.length; i <= len; i++)
    o.push(s.charAt(len - i));
  return o.join('');
}

The above example is a modification of the second example. Instead of using two counters however we use one incrementing value that gets deducted from the total length of the parsed in string. This calculated value determines the position of the next character to be pushed onto the new array (using the ‘push()’ function instead of ‘[]’). The other difference from the last example is that it uses the strings ‘charAt()’ method instead of its array capabilities.

4. In-built functions

1
2
3
function reverse(s) {
  return s.split('').reverse().join('');
}

This implementation takes advantage of the ‘reverse()’ method provided by the Array prototype. First it splits the string into a real array, then calls the ‘reverse()’ method and finally returns the joined array.

5. Decrementing while-loop with concatenation and substring

1
2
3
4
5
6
7
8
9
function reverse(s) {
  var i = s.length,
      o = '';
  while (i > 0) {
    o += s.substring(i - 1, i);
    i--;
  }
  return o;
}

Using a decrementing while-loop I was able to implement this method. Again harnessing concatenation, I was able to achieve the iteration through the string in a similar fashion to the for-loop used in the first two examples. I was then able to use the strings ‘substring()’ function to retrieve each desired character.

6. Single for-loop declaration with concatenation

1
2
3
4
function reverse(s) {
  for (var i = s.length - 1, o = ''; i >= 0; o += s[i--]) { }
  return o;
}

This is most likely my favorite implementation, due to its unnecessary cryptic nature. Using only a single for-loops parameters, I was able to decrement through the parsed in string and concatenate each character to a new string to return.

7. Recursion with substring and charAt

1
2
3
function reverse(s) {
  return (s === '') ? '' : reverse(s.substr(1)) + s.charAt(0);
}

The above example recursively calls itself, passing in the inputted string, excluding the first character on each iteration, which is instead appended to the result. Iterating through this process until no input is present (the base case) results in a reversed string.

8. Internal function recursion

1
2
3
4
5
6
function reverse(s) {
  function rev(s, len, o) {
    return (len === 0) ? o : rev(s, --len, (o += s[len]));
  };
  return rev(s, s.length, '');
}

This is another example of using recursion to reverse a string. The implementation above uses an internal function, which is first called by the outer function, parsing in the inputted string, its length and an empty string. The internal function is then recursively called by itself until the string length has been decremented to zero - at which time the originally empty parsed in string has been concatenated with the inputted string characters in reverse.

9. Half-index switch for-loop

1
2
3
4
5
6
7
8
9
10
11
12
function reverse(s) {
  s = s.split('');
  var len = s.length,
      halfIndex = Math.floor(len / 2) - 1,
      tmp;
  for (var i = 0; i <= halfIndex; i++) {
    tmp = s[len - i - 1];
    s[len - i - 1] = s[i];
    s[i] = tmp;
  }
  return s.join('');
}

I found this method to be a very effective way of reversing a string, highlighting its benefits when processing large strings. The strings half-point is first calculated and then iterated over. Upon each iteration the upper half’s value (calculated by deducting the current position by the string length) is temporary stored and replaced by the lower half’s value. The temporary value then replaces the lower half’s value to finally result in a reversed string.

10. Half-index recursion

1
2
3
4
5
6
7
function reverse(s) {
  if (s.length < 2)
    return s;
  var halfIndex = Math.ceil(s.length / 2);
  return reverse(s.substr(halfIndex)) +
         reverse(s.substr(0, halfIndex));
}

The final method I wish to show uses the same ideology as the last implementation (half-indexing) but instead relies on recursion to reverse the string instead of a for-loop.

Demo

Demo Link