Dataset in React

When life gives you lemons, you make lemonade. And when it doesn’t, hack your way around it. Such was the case with a piece of React code where the previous programmer passed some data-* attributes as props, then onto the JSX markup and later extract them from event.target in the event handlers (or also from the event.currentTarget or from native event). Now, React isn’t ready enough for this (as of January, 2017). The dataset property which are generally accessible via the HTMLElement.dataset property aren’t handled the DOM way.

While playing around wrappers, I had to find a workaround to pass the data-* props. I wrote a little hack to extract the data-* attributes using regex and some spread syntax to pass the dataset to both the outer wrapper, and the inner component.

Example:

render() {
  // Extract the keys present in the `props`
  // Filter the keys which have `data-` as prefix
  // and insert them into `dataset` object
  const dataset = {};
  const { state, props } = this;
  Object.keys(props).filter (value => {
    if (/data-\S+/gi.test(value)) {
       dataset[value] = props[value];
    }
  });
  return (
    <Wrapper {...dataset} onChange={this.handleChange} >
      <Component {...dataset} name="component-type-1">
      </Component>
    </Wrapper>
  )
}

The advantage – you can access the dataset in your handleChange method from the event.currentTarget and event.target. Visit this MDN link to know more about dataset.

Advertisements

webpack sucks, at least for now

Javascript is an interpreted language and by that I understand that when I hit the F5, I expect zero latency for the new script to appear in local dev environment.

When you take that away by introducing obnoxious compilers like webpack – that first needs to be told how to load, then it compiles, then concats before showing me the output, you’re already the subject of my fury.

The ‘wait time’ for compilation sucks

The reasons why I stayed all these years away from coffee script –

  1. I know how to write ‘good’ javascript and
  2. The compilation time – it sucks.

Let JS remain the interpreted language we all know and love. Don’t put your compiled language genius into it. You’re not welcome here – to the interpreted world.

Debugging is horror

you’ve to trace that line out. Imagine a project consisting of 100 small files with almost similar looking content that you concatenated and now clueless where exactly to hunt and debug.

It’s not uncommon – when you write derived components inherited from parent components, the siblings tend to look similar.

webpack – you’re a clutter builder and clarity killer. And, No. I’m not going to work in large files a.k.a monoliths just to support your existence.

Lack of build blocks

I came from an AngularJS Development environment, where I extensively used yeoman and that allows me to work on an index.html file locally which has references to locally kept css and JS.

That means we don’t have to wait for concat or compile before we hit the F5 or ctrl+r.

Plus, the library files from bower_components stay separate. In webpack, unfortunately, they become part of the compilation step.

Luckily, we’ve wiredep and usemin blocks for our rescue – which simplifies local development and gives great support for production builds.

Learn something from it. Your hotness may look tempting to fools and noobs. I ain’t one. Grow up.

Till then – happy hating.

Remedy

And, I always believe there is no point in complaining, one must find a remedy. Following are some workarounds to reduce frustration:

The little catch(es) with Arrow Functions inside Accessors and Methods

Arrow functions are shorthand notation for function expressions. Although the catch is with the binding of this keyword in the context of accessors

Follow the code snippet below:

'use strict';
var obj = {
  a: 10
};

//Snippet A:
Object.defineProperty(obj, "b", {
  get: () => {
    console.log(this.a, typeof this.a, this);
    return this.a+10; // represents global object 'Window'
  }
});

//Snippet B:
Object.defineProperty(obj, "b", {
  get: function() {
    console.log(this.a, typeof this.a, this);
    return this.a+10; // represents current object 'obj'
  }
});

Though the snippets A & B may appear to be working alike, the only catch is with this binding, in the snippet A, where the arrow functions doesn’t bind the this keyword as expected.

I’m a little puzzled, not sure if it’s a bug or a feature, because MDN mentions:

An arrow function does not create it’s own this context, rather it captures the this value of the enclosing context

 

The binding of lexical this takes place differently in case of Arrow functions.

Examples below:

'use strict';
var obj = {
  i: 10,
  b: () => console.log(this.i, this),
  c: function() {
    console.log( this.i, this)
  }
}
obj.b(); // prints undefined, Window
obj.c(); // prints 10, Object {...}

Common Assumption: this.i should behave like any other function inside. NO.

 

Another example involving call (yanked from MDN):

var obj = { base: 1 };
var f = v => console.log(v + this.base, this);
var g = function ( v ) { console.log(v + this.base, this); };
f.call(obj, 2); // logs NaN, Windows
g.call(obj, 2); // logs 3, Object { base... }  

 

The anomaly in the aforementioned snippet ‘A’ is an ‘expected behavior in ES6’ albeit not anticipated in ES5.

Therefore, it can be safely concluded that arrow functions  can well be used for functions, but they are not ideal candidates for Methods. And, as MDN quotes:

Arrow function expression are best suited for non-method function

 

Bonus: Here is a little mindfuck to play around. Try to guess the output.
(() => ({ foo: () => ({ foo: () => ({ foo: () => ({ foo: () => ({ }) }) }) }) }))();

What? It was easy? Nice. Try the next
(() => () => () => () => () => ({}) )()()()()();

Pacman much?
(() => () => () => () => () => {})()()()()();

Update: Updated the same code as examples in MDN

Sublime Text Plugins and Snippets worth exploring – For the modern day

Monokai Neue

Install this first and proceed because a feature has been really missing in sublime.

I use Sublime text 2 and so far it has been my most favourite text editor. My love for it increases with more features I find. Here is a small collection of my favourite set of plugins and snippets and I hope you’ll love them too.

dedicated to all ‘serious front end developers’

Pro tip: For permanently setting a particular syntax highlighting go for View -> Syntax -> Open all with current extension as... ->[your syntax choice]
Compare Side-By-Side

For comparing 2 files, sublime has a built-in file comparison mechanism. Right click on the tab to find ‘compare with…’  option.

Nevertheless, a text comparison tool is definitely a handier alternative and this plugin brings it inside sublime-text.

AngularZen

Sublime text snippets for angularjs developers.

Javascript Beautify

Isn’t it convenient to have such a utility inside the editor. There are some related plugins that you can also hunt for – json formatter, json highlighter, json /xml prettifier etc.

Babel

If you’re working with ES6 too early, then you may like this. This has syntax definitions for ES6 JavaScript with React JSX extensions. You may like Babel Snippets too.

Jasmine Scaffold

This one makes writing your specs breeze. Just write your specs in plain english, indented properly (for describe & it blocks) & hit Ctrl (Win-Alt) (Mac-Cmd) Shift + J.

If you liked that, then you may also find UnitJS even more fun.

Underscorejs snippets

As the name implies, it helps you generate snippets for underscore, a similar package exists for lodash called Vanilla lodash Snippets

Sublime Linter

It requires you to have jscs installed in your machine and a path to a linter executable. A live linter is indeed a necessity in case of an interpreted language like javascript. Not just it saves you from errors, it keeps your code neat if you’ve linters check enabled in your git hooks.

There are some more packages that I’ve not explored yet, but will love to, and they are

Convenience

Dot files Syntax Highlighter

Want ShellScript (Bash) syntax highlighting for your dot files? You’re damn right you do! This plugin is a must for all kinds of developments because you can never get past dot files.

Slugify

Often times you would have desired to slug selected portion of text, this saves your mind

JsRun

A blissful creation from sindresorhus – just select your snippet in sublime, then in the command pallete hit “Run JavaScript in the browser”. Further, you can connect your choice of browser. That’s superb for lazy coders like me.

Focus

When you’re working with your content provider, tweaking minor texts in the static html files, and when text is all that matters to you, then you will love this – another nifty solution from  sindresorhus. This will totally save your day.

Syntax Highlighting for Sass

Its also available for atom & text-mate.

See also: How to exclude Folders from Sublime Text Search

Snippets

Sublime text snippets the most loveable feature I’ve ever found. There are plenty out there, to simplify your daily coding activity. You can write your own code snippets too. There is a decent article on Hongkiat on this too. Here are some snippets that will drive you crazy.

Pro Tip: Make it a habit of routinely invoking the Package Controller, cmd/ctrl + shift + p and typing ‘ip‘. This will highlight the Package Installer. Then, you can search for your beloved set of keywords e.g. Emmet, React, Snippets, JS, json, es6, babel, node etc. and hit enter after selection

Comment Snippets

My most favourite snippet, this makes writing documentation headers smooth. It feels like magic. I fell in love with it in the first sight.

React Snippets

The next generation of snippets i.e. in ES6 for programming with React. Just type React.component and it autocompletes with a code snippet with cursors at the right locations to name your component.

JavaScript and NodeJS Snippets

cd, ce, cl, ae and tons of many other shortcuts to autocomplete your code – if you code in JS everyday, you’ll simply fall in love with it.

Jasmine Snippets

If you liked the Jasmine Scaffold plugin mentioned above, you may also like the jasmine snippets. Unlike the plugin, it’s just quick text to help you with the petty stuff.

Angular Material Snippets

Generates Angular Material snippets for , , as directives referred in the documentation.

TIL: Mozilla’s draft on ES6

Draft ECMA-262, 6th Edition / Draft April 3, 2015 : 

https://people.mozilla.org/~jorendorff/es6-draft.html

Optimized Tail calls in ES6 in Strict Mode

Source Dr. Axel Rauschmayer‘s blog ②ality –
ECMAScript 6 will have tail call optimization: If a function call is the last action in a function, it is handled via a “jump”, not via a “subroutine call”. That means that, if you slightly rewrote computeMaxCallStackSize(), it would run forever under ECMAScript 6 (in strict mode):

    function computeMaxCallStackSize(size) {
        size = size || 1;
        return computeMaxCallStackSize(size + 1);
    }

What is JavaScript’s highest integer value that a Number can go to without losing precision?

Answer: 9007199254740992
Source: stackoverflow.com