Deploying a git subtree to Heroku (or other PaaS)

Most of the common PaaS platforms like OpenShift and Heroku deploy code based on a source in a git repo – you push your local repo containing source to the remote repo on the platform, the build is performed remotely and then deploys the built artifacts.

What if you want to deploy an app that is prebuilt, or you have a git repo that contains various subfolders, and only part of the folder structure in the repo is what you need deployed?

I’ve been experimenting with a simple React app that also has a node.js backend. In hindsight restructuring the source tree to make the app easier to deploy may have been simpler, but it turns out you can push part of your source subtree to a remote repo, like an application deployed to Heroku, using ‘git subtree’:

git subtree push –prefix subfoldername heroku master

This is discussed in this post here.

React Flux Store: addChangeListener is not a function

Using React with Flux, you need to register a callback from your Component so that it can be called when the Store emits an event. For an ExampleComponent and ExampleStore, this might look like:

class ExampleComponent extends Component {

    constructor(props) {
        super(props);
    }

    componentWillMount(){
        ChatStore.on('change', this.handleUserNameChange);
    }
...
}

I’ve seen some examples where a helper function is declared in the Store that registers your Component as a listener, so the call from the Component to register with the Store might look like:

    componentWillMount(){
        ChatStore.registerChangeListener(this.handleUserNameChange);
    }

and in your ExampleStore you’ll declare registerChangeListener() (and similar to remove) like this:

addChangeListener(callback) {
    this.on('change', callback);
}

removeChangeListener(callback) {
    this.removeListener('change', callback);
}

All good so far, but here’s the issue I just ran into:

Uncaught TypeError: _ExampleStore2.default.addChangeListener is not a 
function
 at ExampleComponent.componentWillMount (ExampleComponent.jsx:19)
 at ReactCompositeComponent.js:348

Initially this is confusing, since it’s clear we did already declare addChangeListener, so why is this error saying it’s not a function?

The catch is in how we export the Store. The cause of my issue above was that I had exported it like this:

class ExampleStore extends EventEmitter {
..
}
export default ExampleStore;

This is how you would typically export a module but what we’re trying to do is treat the Store as a singleton instance. To do this the export should be:

export default new ExampleStore();

This approach is described in many Flux related articles (here’s an example), but it’s an easy mistake to miss.

JavaScript ES6 default imports vs named imports

I’d been wondering this for a while. What’s the difference between this style of ES6 import:

import A from './A';

vs

import { A } from './A';

I’ve seen and used both, and had guessed that the { A } syntax is when you’re importing a specific named function from a module? I wasn’t convinced this was correct. It turns out the difference is importing a default export, versus importing using a named import.

This is explained here this SO post here:

http://stackoverflow.com/questions/36795819/when-should-i-use-curly-braces-for-es6-import

Adding react-bootstrap to a React app

Adding Bootstrap to an existing or new React app is not as obvious or easy as you would think, because of Bootstrap’s dependencies on other libraries, like jQuery (and see answers to Quora question here).

The react-bootstrap module is a React specific implementation of Bootstrap that provides JSX components for a number of the Bootstrap provided styles and components, and even layout CSS encapsulated as JSX components like: <Grid>, <Row> and <Col>

Installing it via npm is as simple as:

npm intall --save react-boostrap

You then import what you need from the module like:

import {Bootstrap, Grid, Row, Col} from 'react-bootstrap';

and then you quickly discover that the CSS based layout is not working like you’d expect. If you check the Getting Started section it mentions:

Because React-Bootstrap doesn’t depend on a very precise version of Bootstrap, we don’t ship with any included css. However, some stylesheet is required to use these components. How and which bootstrap styles you include is up to you, but the simplest way is to include the latest styles from the CDN.

Ok. So you can follow their example and load from the Bootstrap (or other) CDN, but what if you want to manage Bootstrap as an npm module too? This question is answered in this post here. What you need is to install bootstrap:

npm install --save bootstrap

and then include it into your main App.jsx with:

import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';

and you’re up and running. Not that obvious but once you’ve setup this once, probably makes more sense the next time.

React: ‘Element type is invalid … check your render method’

Once you’ve seen this error once in your React app you’ll probably instantly recognize it and know exactly what this means:

Uncaught Error: Element type is invalid: expected a string 
(for built-in components) or a class/function (for composite 
components) but got: object. You likely forgot to export your 
component from the file it's defined in. Check the render 
method of `App`.

The key is “You likely forgot to export your component…” which was exactly the issue in my case.

If you have an ES6 style component this:

class App extends Component {
...
}

… check that you’ve exported it at the end of the source file with:

export default App;

Appending values to the end of a file from a Unix shell

Some things you do repeatedly from a *nix shell are incredibly useful and time-saving that you do them without thinking about it. Say for example you need to add a file or directory name to a file like .gitignore. On Windows you might open an editor and add the new lines to the end of the file and save it, but in a *nix shell (I imagine there’s a comparable approach maybe using something like Windows Powershell too), you can do:

echo "newfile" >> .gitignore

and you’re done.

Running a React app in a Docker container

I started converting my AngularJS AddressBook app into React. Since this is part of a larger project to run all the parts of my app in Docker containers with Docker Compose, I needed to look at how I can run my React app in a container.

For development, using the webpack dev server works well locally. Running this from within a container though requires doing an ‘npm install’ and a ‘npm run build’ inside the container, which probably doesn’t make sense to run every time, as with all the npm dependencies from create-react-app this take some time to run.

The other option is to build the app locally and then just build a container with the webpack output, and serve it with an HTTP server like nginx.

Let’s take a look at each of these options.

The easiest and simplest approach is to build the app locally first, as you normally would:

npm install
npm run build

A Dockerfile to build the container using the output from ‘npm run build’ then looks like (using an nginx image as a starting point):

FROM nginx
COPY build /usr/share/nginx/html

You build this with:

docker build -t addressbook-react-web-nginx .

And then run with:

docker run -it -p 80:80 addressbook-react-web-nginx

Next up, for a comparison, the Dockerfile to push everything into the image and run with ‘npm run start’ inside the container would look like:

FROM node:6.10-alpine
RUN mkdir -p /home/web
COPY *.html /home/web/
COPY public /home/web/public/
COPY src /home/web/src/
COPY *.json /home/web/
WORKDIR "/home/web"
RUN npm install
ENTRYPOINT npm run start

This is starting from one of the official node images. It copies in all the source files, runs npm install and then sets the entrypoint for when the container starts to run the webpack dev server.

An improvement on this approach could be to build an intermediate container with the package.json and npm install already run, and then build new images from this incrementally adding just the changed source files. Plenty of options to explore depending on what you need to do.

Next up, modify my previous docker compose file to include one of these new images containing my React app and now I’ve got all the pieces ready to go.

Project Jigsaw for Java has been a long time coming – are we really going to see it in Java SE 9 this year?

Java SE 9 general availability date is 7/27/17, per the release schedule here. Project Jigsaw been a long time coming and been postposed from release to release (it was originally planned for SE7, pushed to SE8, and now SE9), but this year we’ll see Project Jigsaw come with SE 9.

It’s funny what you find unexpectedly when searching for stuff online – reading around for Jigsaw related articles I found this Jigsaw mailing list post by Mark Reinhold back in 2012 including a link to one of my blog posts, discussing the Jigsaw ‘plan A’ vs ‘plan B’ options back when Jigsaw was pushed out from SE 8 to 9. Hopefully we really will see Jigsaw in SE9 later this year.

BASIC 10liner 2017 contest entry – Boulder Jumper

I’ve seen posts about the BASIC 10Liner contest before, but this time I spotted posts for the 2017 contest with time to put an entry together. This weekend I spent a few hours putting together an entry using Sinclair BASIC on an emulated Spectrum, using Fuse for MacOS.

My entry is a take on the infinite runner style games, like Temple Run, but re-imagined in glorious 8 bit Sinclair BASIC style, I’ve called it ‘Boulder Jumper’.

If that’s not enough I went completely retro and implemented the graphics using only characters. This is my first entry to the BASIC 10Liner contest, and the first time I’ve written any Sinclair BASIC for maybe 33 or maybe more years.

My first thoughts were how can you possibly write a fully functioning game in 10 lines of code, but you can have multiple statements per line, and enter in either the 80 chars, 120, or 256 characters per line category. I think I’m just about squeezing into 120 per line.

Here’s a screenshot of the awesome gameplay:

Your character is a ‘b’ character, and rocks come from the right moving to the left, as ‘o’ characters. You press ‘m’ to jump and jump over the rocks or get squashed. You get points per rock you jump over, and have 3 lives.

Here’s the code in all it’s Sinclar BASIC glory:

And here’s the 10 lines in the Fuse emulator:

It’s not great and you could do a lot better (this is probably better suited to a ZX-81 than the ZX Spectrum), but it’s my first attempt for the 10Lines contest, and I had run writing and playing it!

Adding React Router to a React App

react-router is a routing library for React, that allows you to declare which components render based on url paths. It’s similar to ng-route and ui-router in AngularJS.

To get started, install react-router npm module:

npm install react-router --save

Full docs are here.

While working on converting an existing web app to React, I ran into a few issues getting my react-router usage working as I wanted.

Here’s my first attempt adding the Router declarations into an existing Container component that renders NavigationComponent – this Component renders a set of navigation links that are common across each of the pages:

<div>
    <NavigationComponent/>
    <Router history={hashHistory}>
        <Route path="/" component={Home}/>
        <IndexRoute component={Home} />
        <Route path="new" component={AddNew} />
        <Route path="search" component={Search} />
    </Router>
</div>

The first error I ran into was this:

Uncaught Error: <Link>s rendered outside of a router context cannot navigate.

Ok, this makes sense, so I need to move the NavigationComponent that renders my Links within <Router> :

<Router history={hashHistory}>
    <Route path="/" component={NavigationComponent}/>
    <IndexRoute component={Home} />
    <Route path="new" component={AddNew} />
    <Route path="search" component={Search} />
</Router>

Routes at the same level replace each other when rendered. To keep the navigation component rendered with the AddNew and Search as child sections of the nav area, nest the Routes as child elements:

<Router history={hashHistory}>
    <Route path="/" component={NavigationComponent}>
        <IndexRoute component={Home} />
        <Route path="new" component={AddNew} />
        <Route path="search" component={Search} />
    </Route>
</Router>

Now, for the NavigationComponent to render it’s child elements, you need to tell it to render:

{this.props.children}

So now this becomes:

render() {
    return (
        <div>
            <div>
                <nav className="navbar navbar-default" role="navigation">
                    <div className="navbar-header">
                        <Link className="navbar-brand" to="/">AddressBook</Link>
                    </div>

                    <div className="collapse navbar-collapse navbar-ex1-collapse">
                        <ul className="nav navbar-nav">
                            <li className="active"><Link to="search">Search</Link></li>
                            <li><Link to="new">New</Link></li>
                        </ul>
                    </div>
                </nav>
            </div>

            <div>
                {this.props.children}
            </div>
        </div>
    )
}

Here’s a good reference for getting started: https://medium.com/reactspeed/create-basic-navigation-components-using-react-router-475bc55a517f#.itkvn5st9