You are viewing the Articles in the React Category

Quick Tip: React Spring & Babel Loader

Recently, I had integrated React Spring within an Application, and while it is one of the best Animation Libraries for React I have come across in quite some time; unfortunately, I encountered some issues when running tests and production builds.

Essentially, the issues I experienced were related to the imported modules being written in ES6. This was an issue for me as I prefer to have webpack babel-loader configured to exclude node_modules and only transpile project sources.

Fortunately, the work around for this is quite simple: just import the CommonJS modules (i.e. .cjs extensions) rather than their ES6 counterparts (i.e. no extension).

Thus, simply changing:

To:

Resolves the issue.

And so, should you happen to come across build issues when using React Spring, a nice alternative to including the node_modules directory or specific dependencies is to simply import the CommonJS modules.

Separation of Concerns: propTypes and Immutable.js

When considering the separation of concerns between Container and Presentational Components (stateful / stateless components), I find it useful to leverage the core concepts of these patterns in order to define a clear boundary between where Immutable data types are used, and where raw JavaScript types are referenced exclusively.

By having a clear separation which compartmentalizes where Immutable types are used and where they are not, team members are afforded the ability to easily determine a components propTypes; as, without having a clear cut-off point, one must give thought as to if a prop passed down to a component will be an Immutable object, or not.

It’s no stretch of the imagination to see how this can quickly lead to code which becomes much harder to maintain than it needs to be. As such, the Container / Presentational Component pattern provides a rather natural boundary for separating these concerns.

Unfortunately; however, while such a boundary may seem rather obvious, it may not always be clearly defined, and this tends to lead to overly complex propType declarations.

For instance, on a number of occasions I’ve seen propTypes declared similar to the following:

Given the above example, it’s obvious that it was unclear to the original implementor (or current maintainer) of SomePresentationalComponent as to what the expected propTypes will ultimately be. In certain cases, it appears someList could be of type array; whereas, in other cases, it could be of type object (e.g. Immutable.List). Likewise, in some cases someItem could be an object, whereas in others it could be an Immutable.Map.

As you can see, this is obviously problematic and indeed a very good candidate for a bug (not to mention, a maintenance headache indeed).

Moreover, it results in all sorts of unnecessary type check permutations before accessing properties. For example, just to check the length of the list:

Likewise, just to get the id of someItem:

At best, this is far from ideal, to say the very least …

Now, obviously the developer could simply define a single propType and refactor Containers which are passing an invalid type; however, it may not always be clear what the type should be, if say, the component is being used by multiple applications to which the developer does not have access, and some of those applications are not using Immutable.js, in which case, it would be best to simply disallow Immutable from the component all together and have consumers of the component update their Containers. In any event, it’s symptomatic of a team not having a clear understanding of what kind of components work exclusively with Immutable data types, and which do not.

Solutions

Fortunately, as one might imagine, there are a couple of very simple solutions to this problem:

  1. Only use Immutable types throughout the entire application.
  2. Segment which components use Immutable types, and which do not.

Now, in some cases the argument for Option #1 may very well be a valid one; however, I find Option #2 to be much more feasible (and flexible) as, it helps to ensure Presentational component are kept pure, and that means only using JavaScript types. For my purposes, this is especially important as I have to maintain a shared library which must limit dependencies as much as possible; and some projects are using Immutable, Redux, etc., and some are not. As always – consider the context.

Pros

By having an internal design contract (or convention) which mandates that Container components are only ever to work with Immutable types and, Presentational components are only ever to be passed JavaScript data types, it becomes much clearer to team members where the boundary is defined, and thus, much easier to maintain a large application over time.

Furthermore, it allows less experienced developers to gradually become acclimated with the React Ecosystem by assigning them tasks focused on presentational features. This can be very useful as it only requires knowledge of core concepts without being inundated with additional libraries and APIs. This approach also affords team members with more experience to focus on the more complex portions of the application (application logic, reducers, containers, etc.).

In addition, destructuring, …rest parameters and related ES6 features can be used much more extensively to simplify implementation when using JavaScript types exclusively, helping to ensure Presentational components are kept intentionally “dumb”. Not to mention, in doing so, testing becomes considerably less complex when working with native JavaScript types – and this is equally important when helping newer developers become productive while still getting up to speed.

And, while not always likely, by reducing our dependency on Immutable.js, we position ourselves for a much more easier migration path in the event we decide to swap out Immutable for another library in the future.

Cons

Arguably, one could be justified in the assertion that only Immutable Data types should be used by both Container and Presentational components (Option #1), and indeed that would be a fair argument if you will be calling toJS() frequently when passing props down to Presentational Components (as there is obviously an inherent expense in doing so).

That being said, there is no reason why one would need to call toJS when passing props to Presentational Components as the Immutable API can be utilized to reduce the given props before being passed down to child components. In such cases, a Higher Order Component can be defined for doing either, which can simplify implementation considerably.

Summary

Like most design decisions, there is rarely a one-size-fits-all approach that perfectly solves any given problem, and what ultimately makes sense in one context, may not always be appropriate in another. However, in the context of when and where Immutable types are used, in most cases it is fair to say there should always be a clear boundary defined, regardless of where that boundary must be.

React PropTypes and ES6 Destructuring

At times one may be justified in the argument that cognitive (over)load is just an expected part of the overall developer experience. Fortunately, there are numerous steps we can take to minimize the general noise which tends to distract our intended focus. One particularly simple – yet effective – example is to remove unnecessary redundancy wherever possible. In doing so, we afford both our peers and ourselves a codebase which, over time, becomes considerably easier to maintain.

For instance, when performing code reviews, more often than not I tend to see considerable redundancy when specifying React PropTypes. Typically, something along the lines of:

As can be seen, with each new prop we are redundantly referencing React PropType lookup paths. And, while the ideal components will have a limited number of props (either connected directly, or passed down), the redundancy still remains for any component which references the same prop type. Considering the number of components a given application may contain, we can rightfully assume that the above redundancy will grow proportionally.

With the above in mind, we can easily reduce the redundancy (as well as micro-optimize the lookup paths) be simply destructuring the props of interest as follows:

While I would consider the above to be simplified enough; one could also take this a step further and destructure the isRequired props, which, in some circumstances, may be useful as well:

Admittedly, this example is rather straight-forward; however, it does help to emphasize the point that only through consistent vigilance can we ensure our source will continue to evolve organically while remaining as simple as possible.

React-Bootstrap ES6 Imports

When leveraging React Bootstrap, one important consideration missing from the documentation (or perhaps, simply not emphasized enough) relates to module access when using ES6 imports.

Specifically, in the context of React Bootstrap’s “convenience components” <Component.SubComponent> (e.g. <Modal.Body>), such imports must be made explicit as they can not be resolved against their parent components during transformations of ES6 imports to CommonJS modules.

For instance, one can not reference sub-components as follows:

During transpilation, the above reference will result in Babel (specifically, the babel-plugin-transform-es2015-modules-commonjs module) causing an upstream exception:

Property object of JSXMemberExpression expected node to be of a type [“JSXMemberExpression”,”JSXIdentifier”] but instead got “MemberExpression

Fortunately, the solution to the issue is rather straight-forward; simply import the sub-component explicitly via react-bootstrap/lib , for example:

With the above example, the previous conversion errors will be resolved, and all will be well again.

Overall, I actually prefer the explicit imports (though it would be more convenient if they were exported via ‘react-bootstrap’).

And so, for the time being, a minor nuance worth noting should you find yourself trying to diagnose this issue at some point.

Quick Tip: HTML to JSX Conversion

Like many developers, at times I find the need to convert raw HTML to JSX. It was only after I found myself needing to do this a bit more frequently that I considered writing a quick tool to automate the task. However, like most things, I knew there must be something out there which handles this already, and as I suspected, there certainly is: HTMLtoJSX – a component of React-Magic which does precisely this.

So, if ever you need to quickly convert raw HTML to JSX, be sure to check out the online converter and, for more frequent needs, the converter is also available via NPM and can easily be integrated into part of an existing build pipeline.

Back from the Peripheral

Hello again…

Indeed, a greeting may be appropriate here as it has been quite some time since I have actively blogged which, for all intents and purposes, has been for good reason.

After a decade of continuous blogging with a minimum of at least one (hopefully) informative article per month, I had made a conscious decision to take a step back, re-evaluate, and, on the peripheral, dedicate my otherwise allocated writing time towards focusing on the many aspects of future Web Development.

With that in mind, my time spent has been put to good use, and so, I’ve decided to begin sharing my experiences here more frequently once again; both trivial and non-trivial alike.

The fact is, I miss writing, and outside of day to day writing of general API docs and the occasional technical spec, I haven’t had a dedicated space to share my more subjective, creative thoughts about modern Web Development. Enough about me, though, I’ll get to the point…

Before I delve into the specific topics I plan to discuss, I think it makes sense to first outline an underlying theme which will permeate throughout my future articles. Specifically, I plan to to focus on topics and technologies which I believe will, to a certain extent, transcend the more immediate trends within the Web Development landscape that tend to come and go with the times. I strongly believe it is essential for our community to continue on a path of sustainable growth, and the path of least resistance will more than likely be in our ability to move from library to library, framework to framework, easily and with minimal transition. This is imperative as the rate at which technologies are changing has grown exponentially in the past few years, perhaps no where more so than in the Web Development space. As such, the ability to identify and focus on core underlying concepts, principles and technologies which will remain relevant for some time to come becomes ever more important.

The simple fact is, we need to pay particular attention to what we dedicate our time to learning, and ensure our learning is focused on key aspects that can carry over as each new technology increases in adoption, and then makes way for the next in line.

With that in mind, I plan to focus this space on my findings and most recent experiences with current Web Development technologies of interest, particularly, but not limited to, the recent work of the TC39 Committee, all things ES2015 / ES2016, React / Redux, Webpack, Web Components, Polymer, Angular 2, and the many other complimentary tools and technologies surrounding modern workflows.

So stay tuned, as always, there’s a lot to talk about! Good things to come …