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.

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:

http2, https and more

Before we begin anything, let these information sink in. Watch the following video:

URL: www.heavybit.com

Long back when I was serving an eCommerce major, our team evaluated HTTP2 over http and it was concluded that the gains were minimal. TBH, I felt our premise was wrong, our approach for evaluating http2 was unduly done (read ahead to know). It was later concluded that we were not going for http2 because it had low ROI.

Right now, in my current org., I tried to push through http2 along with https (https because of the reasons mentioned ahead). My proposal wasn’t accepted, again because of Low ROI.

There are several costs associated with going with http2 + https viz

  • Investing on procuring an SSL certificate
  • Evaluating nginx 1.9.5
  • Reading through the documentation and setting up the nginx.conf
  • Troubleshooting on staging / prod environments
  • Change in build script to optimize the outputs for http2 protocol
  • Despite being least of our concern, lack of support in legacy browsers is kind of inhibiting if your priority is to get everyone onboard.
  • Another small concern is over 3rd party tools – all web apps use premium (not free) 3rd party tools to study user behavior. Checking their compatibility with https is important again. (Small concern – because most 3rd party tools realize this & they serve their contents from https. But there could be smaller players who do not have this capability).
  • Change of origin – A change in protocol i.e. from http to https will change the port from :80 to :443. This alters the URI schema. Hence, it’d also imply that the origins have changed. Although, I’ve not validated this or the areas of impact, but it impacts the current SEO or anything else, it’ll be a bigger concern to us than anything else
  • Non-secure content – We load our static assets from CDNs and thankfully, Amazon cloudfront supports both http and https. But, if any of our providers failed to provide us with an https endpoint, we’ll be hopeless

Reason for going with https:

  1. The idiosyncrasies associated with proxy servers and anti virus software to sniff unencrypted http1.1 content. And, if they spot any anomaly in headers e.g. the http version, they’ll simply flag the content as malicious
  2. Google Chrome is anyway going to shame non-https websites
  3. https has elevated priority in SEO ranking over non-https. At least, Google obeys this and as a JS-dynamic-template-heavy website, my sole hope for SEO is Google’s Page Rank algorithm alone.

What went wrong with our previous http2 evaluation

http2 is not just the version digit incremented. The transition of the version no. indicates that the new version is a total paradigm shift from the earlier version. http2 protocol works better on small splitted files – hence, our age-old practice of concat-minify-obfuscate-revv won’t work.

Key takeaway 1:

To get the best out of http2, you need many small files minified-obfuscated-revved, not concatenated into single file.

Check these link to get a better idea on the goodness of many small files:

Bonus tip: For a cherry on top the cake, you can further use AMD to load modules whenever needed.

Our last evaluations were based on testing speeds with single-large files. Hence, the gains looked minimal. HTTP2 wasn’t designed perform better with large files.

Key takeaway 2:

Domain sharding is no longer a requirement.

To parallelize static asset loading, we heavily depended on domain sharding i.e. splitting resource requests across multiple domains thereby opening multiple TCP connections.

http2 doesn’t require that. Multiple static resources should be requested over one and only one TCP connection. Unfortunately, this was not how we evaluated.

Key takeaway 3:

Encrypted connection i.e. https is not slow. Google’s SPDY protocol, which could be enabled by just enabling another flag, was the best way for loading resources https, until http2 came in.

It had to be good enough for Google to declare its annihilation/ further usage & support.

What to do next to convince your team to go for http2 + https

Every decision in an organization should be based on facts, based on data a.k.a. Data driven decisions. Decisions can’t be made on the basis of popular remarks/opinions. So

  • Gather data about https adoption across industry
    • gather all benchmarking studies and results
    • gather its success stories
    • perform your perf tests on your existing system and gather benchmarking data
    • analyze performance data from http2 & utilize this data to show comparisons
      • e.g. if your new server gives a time boost of even a thousand milisconds, that’s a major save
    • PS: performance tests can be baffling and overwhelming. One feels as if they’re part of some Formular 1 team doing performance improvements
  • Clearly explain the need of encryption and how encryption leads to greater trust and security
  • Make everyone understand that SSL certificates are no longer hard-to-obtain
    • Companies like startssl can offer you a free ssl certificate to get started with
    • Additionally, your bash console comes powered with openssl tools. You can leverage it to create a self-signed certificate for your dev environments
  • Start your POC
    • fork your repo, create an experimental branch
    • Perform benchmarking tests
    • and, do an A/B test
    • Check the conversion rates on each system

I’m using Node.JS / Apache. How can I go for http2?

At the time of writing this article, I’ve n’t explored about Node.JS support for http2. There could be libraries to help you out with this. Or may be, Node inherently support http2 out of the box. I do not know yet. (will update this post when I figure it out). Same applies to Apache as well.

However, nginx 1.9.5 has http2 enabled. Therefore, you can always put an nginx proxy in front of your current server – be it node.js or apache, or any server.

  • Setup nginx 1.9.5 on your box
  • Specify http2 with ssl along with http
  • Upload your certificates & configure the server correctly
  • Run your nodejs server on a different (system unreserved) port (you can block this port from public access too)
  • Configure the nginx proxy to consume data from nodejs server

This will ensure that nginx (which is well maintained and free and also supports the required http2 + https setup) will take charge of encrypting & http2-fying your site while your nodejs app keeps working the way it has always been.

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.

Common issues Frontend Developers run into

1. Using ‘sudo’ with ‘npm install’ Why can’t I npm install nodemon or supervisor on OSX 10.8.4?

Update: Finally npm has updated the instructions to fix the npm permission errors, click here to know more.

  • Often times when installing an npm package, you might have encountered EACCES errors.
  • They result primarily because of directory permissions
  • To curb it, people go with sudo which is not advisable. Using sudo with npm install is potentially unsafe
  • There are solutions like npm cache clean. But cache clean do not address the root cause.

Solutions:

This issue is with the ownership of the npm packages directory

i.e. /usr/local/lib/node_modules/*.

To solve the issue, you need to set the ownership on the npm packages directory and its parent i.e. /usr/local/ directory to yourself i.e. the admin user:

sudo chown -R $USER /usr/local
sudo chown -R $USER ~/.npm

  • In some of the cases you may face similar EACESS issues, not with the NPM’s node_module cache, but in your own project folder. In such a case, just
sudo chown -R $(whoami) $(npm config get prefix)/{lib/node_modules,bin,share}

You may encounter the following issue even after doing the above:
Insecure world writable dir /usr/local in PATH, mode 040777

If you still get errors like the one above from compass, you have to follow this link. If that doesn’t work out, re-install ruby, and compass.

2. Using ‘gitk’ from ‘cmd’ or ‘cmder’ on Windows

Unlike bash-compatible shells like mingw (comes with git for windows) or cygwin, some advanced command line tools like cmder can’t invoke 'gitk' straight away.

Solution is running gitk.cmd instead.