Embracing the Future of Front End Development at Mudbath

June 18 - Matt Sikkema

"I'm looking for new challenges" is a standard platitude when leaving your job, and it's one that I used too - although in my case it was true. At Mudbath Digital there is a focus on spreading out and adopting new technologies, and is where I got hands on experience with React and modern JavaScript.

 

I was primarily a regular JavaScript and Angular 1/Vue developer - and when I say regular JavaScript, I mean JavaScript prior to ES6. Like many web developers, I had watched with some interest as drama started to arise over such large changes to an important, widely used language with no benevolent dictator to force through a single unified vision of what the language should be, so like many web developers, I decided to sit out the entire affair until things had stabilised.

 

As far as ReactJS was concerned - I had a basic understanding of the framework, but was immediately put off by the unholy union of view and view logic that was JSX. The thought of combining the two was horrifying, how could anything good ever come from that, right?

 

React and ES6 at Mudbath Digital

 

It turns out ES6 is too good to ignore - even if it's not widely supported, and the strange beast that is JSX proves to be powerful tool when used correctly. After working with these two technologies together, looking back at my old Angular 1/regular JavaScript code feels like a strange archaeological dig where the inhabitants had yet to discover the wheel.

 

I'm going to spend the rest of this post explaining why React + ES6 has been such a revelation for me, and if you're still using regular JavaScript or don't understand what the fuss is about React, hopefully this will enlighten you. It's by no means a definitive guide, but I will cover the features I like the most.

 

The Good Stuff

 

JSX Makes things flexible

Some projects at Mudbath Digital use Contentful to manage the actual content of a website. This has several benefits - it means that a content team does not need to be shackled to the development team, and changes can be quick and painless to make. Contentful also provides a sophisticated UI so Mudbath Digital can focus on making the website itself, rather than providing workflows and support for the content team.

For these websites, Mudbath Digital creates a project that reads content in from Contentful, then produces a dynamic, consistent and easy to update website. This is is made possible by React and JSX - because the view and view logic is the same and exist inside a React Component, those components can be passed around, decorated with extra functionality, modified based on arbitrary logic and even re-used in other projects.

React also has the concept of stateless components. This allows you to remove any extraneous functionality (read: unexpected behaviour and bugs) from your component if it does not require it, this allows its behaviour to be managed further up the object hierarchy in our projects (for example, by Redux).

 

Destructuring and String Templating are handy

function buildLivesAtString (person) {
    var streetNumber = person.address.streetNumber;
    var streetName = person.address.streetName;
    var name = person.name;
    return name + ' lives at ' + streetNumber + ' ' + streetName;
}

 

Gross.

Lucky ES6 lets you do this:

function buildLivesAtString (person) {
    const { address: { streetNumber, streetName }, name } = person;
    return `${name} lives at ${streetNumber} ${streetName}`;
}

 

Destructuring will return an `undefined` if the variable you are attempting to extract doesn't exist. As seen above, you can extract nested objects quite easily. You can also alias the variables to a new name if you wish. For front end developers, string templating means no more of this all through your code:

return 'first part of string ' + someVar + ' last part of string';

 

Destructuring can also be used in method parameters, so you can simply extract the variable relevant to your function directly to minimise syntactic noise in your code.

 

Spreads

I'd never seen this operator prior to working with Mudbath Digital (Groovy has a feature of the same name, but it works very differently). It takes the content of the spread object and adds them to the parent object it is being spread into, so:

const address = { streetName: 'Hunter Street', streetNumber: 710 };
const business = { businessName: 'Mudbath Digital', type: 'Digital Agency' };

const details = { ...address, ...business };

 

Here, the object `details` will now be of the following structure:

{
    streetName: 'Hunter Street',
    streetNumber: 710,
    businessName: 'Mudbath Digital',
    type: 'Digital Agency'
}


This seemed like fluff to me when I first saw it - except I find myself using it all the time, and even missing it when going back to other languages. One use is passing props to a React component, rather than

const personProps = {
    firstName = 'Christine',
    lastName = 'McVie',
    onClick () {
        console.log('I have been clicked');
    }
};

return ();


You can spread the person props directly without passing each through an attribute:

const personProps = {
    firstName = 'Christine',
    lastName = 'McVie',
    onClick () {
        console.log('I have been clicked');
    }
};

return ();

 

Smarter Object Literals

Old and busted:

var magicNumber = 12345;

function combine(person, address) {
    return {
        name: person.name,
        age: person.age,
        magicNumber: magicNumber,
        address: address,
        newFunc: function () { console.log('I am a function') }
    }
}

 

New hotness:

const magicNumber = 12345;
const combine = (person, address) => ({
    ...person,
    ...address,
    magicNumber,
    newFunc () { console.log('I am a function') }
})


Ignoring the spread operator which we just covered - the magic number field does not need the silly looking `magicNumber: magicNumber` syntax in ES6, rather by dropping a variable straight into an object literal, this creates a new field in the object where the key is the variables name, and its value is the value of the variable. The fat arrow notation also avoids the need to wrap the literal in a return statement, and the function syntax now matches the regular function syntax for ES6 classes. It's the small things in life.

 

Redux is nicer to work with

We use Redux for some projects, a non es6 reducer may look like:

var initialState = {
    personName = 'No Name',
}

function greetPerson(state, action) {
    if (typeof state === 'undefined') return initialState;

    switch (action.type) {
        case UPDATE_NAME:
          var newState = jQuery.extend({}, state);
          newState.personName = action.payload;
          return newState;
    }    
}


But in ES6 land:

var initialState = {
    personName = 'No Name',
}

function greetPerson(state = initialState, action) {
    if (typeof state === 'undefined') return initialState;

    switch (action.type) {
        case UPDATE_NAME:
          return {...state, personName = action.payload};
    }    
}

 

Note that if spreading multiple variables of the same name, the last spread variable will overwrite the earlier ones. This means we can simply spread the original state into a new object, and then overwrite the state variables that need to be changed.

 

The Not So Good Stuff


Modern JavaScript is still unsettled

While there are many features that have been confirmed, there are still lots that haven't. Writing a codebase with features that may still be yanked at the last minute is not the best situation to be in, but using those feature is still an overwhelming net win for developers.

 

Babel is confusing

There are many situations where we need to transpile our code to work properly. Babel's website is enormous, confusing, and we find ourselves needing many separate plugins to get the transpiling to occur directly. Adding async/await support for example, is not straightforward process. Babel has also moved their NPM packages to comply with the new naming convention, and the renamed packages are often not compatible with the older style packages.

 

JSX has some shortcomings

JSX has parts that caused me confusion - Most of the time the attribute name in HTML is transformed into camel case for JSX, yet the `class` attribute is `className` in jsx (presumably because `class` is a reserved keyword in JavaScript, and there are cases such as `tabindex` becoming `tabIndex`, despite the attribute being a single, uncapitalised word in HTML. `{/* code comments also look silly */}`. Basic operations like looping to generate a UI element is a pain in the butt, and in future, moving to the latest javascript framework could be difficult on account of the view and view logic layers being glued together.

 

Overall


There's much to be gained by adopting the latest stuff - sure there are bound to be parts that are untested and maybe problematic, but on the other hand these new technologies become popular for a reason, not because they are worse than the existing solutions they aim to better or replace, and that's certainly the case with React and ES6 JavaScript.

 

So the next time you're at your desk, staring at your enterprise PHP, trying to avoid that one weird coworker who wears headphones everywhere (even to the bathroom) and brushes his teeth in the sink, or wondering just who the Lunch Thief really is, and you start having that fantasy about whipping out your resignation letter and slamming it down on your manager's desk as if it's a giant paper sword, keep in mind that looking for new challenges isn't always the empty cliche it's made out to be.