React

meteor logo

Introduction

Meteor has become the go-to Javascript framework for our team. We use it in combination with React on the front-end. I thought I would write a quick tutorial to get started with Meteor + React. In addition, I’ll also touch on FlowRouter for the routing. If you do not have Meteor installed yet, you can follow the instructions from this page
Continue reading Meteor, React and FlowRouter: Quick Setup

Read more

crazy homer simpson

Introduction

This is just a little article to share a problem I encountered. I was tasked with building a CRM and transactions had to be filtered by date. Nothing fancy about all this. You check if the transaction’s date is between two other dates the user gives you ( a start date and an end one ).

The code

Well, here is how the code looked before I managed to solve it. I was using React with this code. I used the popular javascript library moment.js to work with dates.


renderTransactions(){
    return this.props.transactions.filter( transaction => {
        const start = moment(this.state.startDate)
        const end = moment(this.state.endDate)
        const tDate = moment(transaction.date)

        return tDate.isBetween(start, end) // Compare dates here
    })
    .map( ( transaction, i ) => {
        transaction.date = moment(transaction.date).format('DD/MM/YYYY')
        return (
            
                {transaction.amount}
                {transaction.date}
                {transaction.client}
            
    })
}

// etc.. etc...

Ok, can you see where the problem is? The first time the component renders, everything is fine, the dates are properly filtered. But, as soon as I modify the dates, nothing works anymore…

The problem was here:

transaction.date = moment(transaction.date).format('DD/MM/YYYY')

See how stupid that is? I mutate the state of my array with this line. On the next render, the date field is not longer a Date object that the moment library can work with, but a String…

Solving it, and restoring my sanity…

Take one:

Don’t use this.props directly. If I used a reference to this.props.transactions in my function, the problem wouldn’t have happened. Every time the function would run, a fresh copy of this.props.transactions would be used. Even if I kept the problematic line with the direct mutation, it would work.

Take two:

Immutability. Don’t mutate the state of your application directly. This line would have solved everything:

const date = moment(transaction.date).format('DD/MM/YYYY')

Done… Problem solved.

Conclusion

I’m just writing this to make sure I don’t make the same stupid mistake again. I spent way to much time on this… I’m tired and I hate programming.

Read more

What I worked on

It has been more difficult to find the time this week. I managed to squeeze in a few hours this week-end. So, the catalog is starting to take form. The game’s cards are classified by classes and sorted by mana cost. I added previous/next buttons to switch pages ( 14 cards are displayed on each page ). I had a little challenge when I had to switch from one character to the next. When you click next and the current character has no more cards, the application switch to the next character and displays its cards. Took me some time to figure out though.

I mostly worked on the HomePage this week-end. I styled the navigation bar slightly, and I added buttons for the Add new game and Create new deck actions. The new game action opens a modal where the user can choose 4 things:

  • its class
  • its opponent’s class
  • its deck
  • the outcome of the deck

The modal is done and the front-end logic is handled.

Next week goals and code

For this week, I will try to finish the new game functionality by inserting them in a database and listing them on the front-end. I think the future statistics page will display a list of the latest games saved. Then, I will start the creation of the new deck functionality. This might take a while. Not quite sure how a want to do it yet. I think I will add an action on each card in the catalog to allow the user to add the card to a deck.

The code can be found here

Read more

Every week, I write a blog post about my progress on side projects. I explained my thought process in this article last week. I also detailed the first project that I wanted to work on for this month.

Week One

The stack choice

For the front-end, I went with React and create-react-app. It greatly reduces the headache of getting everything set up. For the back-end, I chose express. For this project, this is more than enough to do what I want. I’ll also use MongoDB for the database and I decided to use semantic-ui for the UI framework. I used material-ui before, so I went with a different one.

Setting things up

There are two different parts in this project. The root of the project takes care of the server side ( express + mongodb ). Inside this root folder, a /client folder holds the front-end that was set up thanks to create-react-app.

The first difficulty that I had was to connect both parts. How do I inform the front-end and back-end to listen to each other with the create-react-app setup?

Thankfully, the documentation links to a tutorial that explains how to make create-react-app works with an API. Right here if you’re curious. The front-end and back-end are run concurrently thanks to the npm package named concurrently ( convenient ).

And after that, I could start writing my code.

Hearthstone API

To get all the informations about the game’s cards, I found an API at this url. Well documented, easy to use, and I have all the informations I needed.

React Router

This one made me sweat a bit more. I wasn’t aware a new version of React Router was released. It took me some time to understand how the new one worked. ( BrowserRouter and Switch ).

Starting to see some results

I started with the cards’s catalog. I had to figure out the call to make to get the cards I needed ( hint: collectible=1 ). After that, I filter the cards by classes and sets in the front-end. Hearthstone has a “standard” mode where only the most recent cards sets are used.

The catalog functionality will ressemble the one in the actual game. The user should be able to sort them by name, mana cost, cards set and classes…

Code and next week’s goals

Here is the code on Github

For next week, I will try to finish the catalog functionality with all the sorting and filters. If that is done, I’ll start adding some deck actions ( deck creation, adding cards to deck from catalog … )

See you next week!

Read more

Introduction

In this article, I will give you a quick overview of Webpack. As you may know, JavaScript is everywhere, so the number of tools created by the community increases as a consequence. It is most certainly the sign of a very healthy environment. We, as developers, are trying to improve our workflow, make better products, and make them available for a wide variety of users. But, when you are in a learning process, it is extremely easy to become overwhelmed by all the possible things you can learn. You may have read a few articles about ‘JavaScript Fatigue’ like this one or this one.

As I keep trying to improve my skills as a developer, I can start to recognize a pattern in the most popular tools, libraries and frameworks. React is becoming ( or has become already? ) a very popular library. But, with React, you may have heard about a tool called Webpack. Webpack is a very powerful tool. I’ll try my best to make it as understandable as possible. Here is what I will cover in the article:

  • What problems do Webpack solves?
  • A quick start with Webpack
  • Adding the webpack.config.js
  • Webpack with React

Let’s jump right in!

1) What problems do Webpack solves?

If you are familiar with JavaScript, you may already know about modules. Modules allow us to separate our code into small files to make it more readable and modular. Then, we can export and import those modules in other files when we need them. It makes our code DRY(don’t repeat yourself), easier to test, debug… Well, it’s just awesome.
Node.js use a module conventions called CommonJS. You can find more information about it here. Basically, you use require() to import modules from other file, and the module.exports object to export them. Something like this:

hello.js

const hello = function(){
    console.log('Hello World');
}
module.exports = hello;

sayHello.js

const helloFunc = require('./hello.js');
helloFunc(); // Hello World

Now, all of this works great in the Node.js environment. The CommonJS modules are the default mechanism and ES6 syntax is supported, because the engine that runs Node.js keeps up with the JavaScript standards. The problem comes with the browser space. The browsers have a very fragmented way to support modules. Some browsers have a environment that supports CommonJS modules, just like Node.js. But other browsers might support a environment based on AMD (Asynchronous Module Definition) loader (RequireJS for example). And some browsers don’t even have a module system at all, meaning that they use globals to access other modules.

So, how do I make sure that the I can use the modules I write in every browser? Enter Webpack. Webpack is a module bundler. It allows us to write modules just like you would do it in Node.js. Webpack will then scan your require() statements and resolves the references modules into a bundle. Webpack goes through a compilation step and creates a bundle(single file) that you can easily include in a web page. If this sounds a little complicated, don’t worry, I’ll show you some examples!

2)A quick start with Webpack

Let’s see a real example of Webpack in action.
First, you need to install Webpack. Go to your terminal and type:

npm install -g webpack

Note: you may have to sudo for this.
Now, let’s create three files: main.js, sayHello.js and index.html.

In main.js, let’s write a simple module:

module.exports.sayHello = function(name){
	return 'Hello ' + name ;
};

Nothing crazy, we populate the module.exports object with a sayHello method. this method is a anonymous function that takes a name parameter a return string with that name. As you can see, we are using the CommonJS module pattern with module.exports (just like in Node.js).

Next, let’s write our browser code in sayHello.js :

var sayHello = require('./main.js').sayHello;
var hello = sayHello('My Dear Browser');
var body = document.getElementsByTagName('body')[0];
body.innerHTML = hello;

Here, we import the module with require(). Then, we use vanilla JavaScript to call the function, get the body element, and insert our string inside of it.

Now, here comes the magical step. In your terminal, run this command:

webpack sayHello.js bundle.js

We tell webpack to compile the sayHello module and bundle all the required dependencies inside a single file called bundle.js. Now, we can use this in the browser.
To use it in our index.html, add a script with the src attribute equal to bundle.js.

That is all we need to run our code. Open your index.html file in your browser and tadaaaa !
Cool, right? But this is just the tip of the iceberg. Webpack has many other advantages:
-Webpack can generate bundles for different modules
-We can use third-party loaders and plugins for almost everything: ES2015, CoffeeScript, TypeScript …
-Webpack can pre-process our stylesheets, images, fonts …
-Can be runned from task managers such a grunt or gulp
-Webpack has a watch mode, meaning we don’t have to run the command from the terminal after each change.
And many many more…

3) Adding the webpack.config.js file

To go a little bit deeper with Webpack, we will use a configuration file called webpack.config.js. This file exports a configuration object that will be read by Webpack when we invoke it without any arguments in the terminal.
Let’s say that, in our previous example, we wanted to use ES2015 (ES6) syntax. Well, we can configure this in our webpack.config.js file. But first, for clarity, let’s move our main.js and sayHello.js files into a src/ folder. Let’s change those files with some ES6 syntax.

main.js

module.exports.sayHello = (name)=>{
	return 'Hello ' + name;
};

We use the arrow function syntax here.

sayHello.js

const sayHello = require('./main.js').sayHello;

const hello = sayHello('My Dear Browser');
let body = document.getElementsByTagName('body')[0];
body.innerHTML = hello;

Here, we use const and let keywords.
Let’s create webpack.config.js in the root of our directory (not in the src folder!) and type:

const path = require('path');

module.exports = {
	entry: path.join(__dirname, 'src', 'sayHello.js'),
	output: {
		path: path.join(__dirname, 'dist'),
		filename: 'bundle.js'
	},
	module: {
		loaders: [
			{
				loader: 'babel-loader',
				query: {
					presets: ['es2015']
				}
			}
		]
	}
};

Ok, let me explain. The entry defines the entry point, and the output defines the destination of our bundle file. In the previous examples, those were the first and second arguments we gave after the webpack command in our terminal. Next, in the module object, we define the loaders. We know that we need to compile our ES2015 (or ES6) syntax back to ES5 where every single browser can read it. So we use Babel for this. The loaders is an array of objects that defines each loader. For this example, we only use one, but we can use a lot more.

Before running this: we need to install Babel and the ES2015 preset:

npm install babel-core babel-loader babel-preset-es2015

Great, last thing, don’t forget to change the path of your bundle in your index.html as dist/bundle.js. As you can see in the output of our file, the destination is in the dist folder now. It is considered good practice to keep your source files and your bundles separated. Now, you can simply run:

webpack

And, now, you have a new folder dist that contains our bundle. And every browser can understand our syntax thanks to Webpack and Babel. Yay!

Note, to launch the watch mode, you can run: webpack -w

4) Webpack with React

A lot of people are drawn to Webpack because of React (at least I was). So, in this section, we will talk about configuring your Webpack to work with React. Compared to the last section, there is not that much configuration required. What is the difference between the code we wrote before and React? Well, you most likely write you code in JSX, the JavaScript superset that makes React easier to work with. So, we need to tell our Babel loader to compile JSX into ES5 code. We just need to add ‘react’ in the presets array like this:

loaders:[
    {
        loader: 'babel-loader',
        query: {
            presets: ['es2015', 'react']
       }
    }
]

Let’s create a new folder. Create two files, webpack.config.js and index.html. Then, create a src folder. Inside this one, create two files, main.js and greetings.js. Our Webpack configuration file will look like this.

webpack.config.js

const path = require('path');

module.exports = {
	entry: path.join(__dirname, 'src', 'main.js'),
	output: {
		path: path.join(__dirname, 'dist'),
		filename: 'bundle.js'
	},
	module: {
		loaders: [
			{
				test: path.join(__dirname, 'src'),
				loader: 'babel-loader',
				query: {
					cacheDirectory: 'babel-cache',
					presets: ['es2015', 'react']
				}
			}
		]
	}
};

The only change is in the presets array.
Note: We are NOT in the same folder than the last section! But I use the same folder names here. You can change them as you please.
Let’s write some React in our greetings.js :

Nothing crazy. Import React and create a component that iterates through the names array. Let’s write our entry file, main.js:

main.js

const React = require('react');
const ReactDOM = require('react-dom');
const Greetings = require('./greetings');

ReactDOM.render(, document.getElementById('main'));

This file imports the component Greetings and renders it inside the index.html.

Now, you need to run this command into your terminal to get all the necessary dependencies:

npm install webpack babel-core babel-loader babel-preset-es2015 react react-dom babel-preset-react

Compared to the last section, we added the react, react-dom and babel-preset-react dependencies.
Now you can run webpack in your terminal and open your index.html and you can see your magnificent component in your browser. Awesome!

Webpack is a very powerful tool that will become more and more useful as your applications grow. This article only describe a small portion of what Webpack is able to do. I believe it should be enough to be able to play around with it.
You can find more information on the Webpack documentation here.

As always, feel free to share, ask questions or correct me if I made a mistake.
Have a nice day!

Read more