How I fell in love with React (Part 5): Miscellaneous

Enzo Ferey
7 min readOct 17, 2016

--

I did this, you can use this image for whatever you want if you credit this series of articles :)

This is the fifth chapter of a series of articles called “How I fell in love with React” where I will share with you everything I have learnt and done in my first month using React (from August 15th to September 15th, 2016).

You can find past chapters here:

In this chapter I am talking about different concrete things that I found in my way along the last 10 days of the month. As they aren’t related to each other, I have clearly separated them parts so you can skip one if you don’t find it interesting.

Enjoy the read !

JavaScript is important

After the component publication on npm, I felt very happy about all I had learnt. However there was still something that was making me diffident about starting a professional project with React: JavaScript.

Of course I have some intuition and I am learning it easily because of my experience in other programming languages. But some concrete things like imports/exports or ES6 syntax weren’t very clearly for me.

Sure I was using them already as you saw in past chapters, but only because I had tweaked some already existing code. I wouldn’t be able to build from scratch something not similar.

That’s why I searched for a ES6 tutorial/course. And… I didn’t really find what I wanted until I came across Wes Bos“ES6 for everyone” course.
Even if it wasn’t free, it was exactly what I needed: beginner level to more advanced stuff along with emphasize on most important features.

I strongly recommend it. The videos are pretty cool, well explained and have a perfect length to complete them without becoming bored.
Worth your money ! (Plus he does a discount for students)

I am not getting anything from him to talk about it by the way

Some ES6 sharing

So I decided to explain briefly the two most commonly used features in React projects.

Import — Export

Those two keywords allow us to modularize our JavaScript code.

When we say module, we are referring to something from one file that we want to use in another file (that could be in the same project or another one). That “something” could be a simple variable, a function or a whole React Component (being the last the most common for us).

In ES6 they are basically two kind of imports — exports.

1) Default import — export

// file1.js
const a = 5;
export default 5;
---------------------------------// file2.js
import a from './file1';
// Notice the need to specify a path to a file because it’s not a // npm package and how we omitted the .js extension.

The benefit from default export is that you can rename the variable on the other file:

// file1.js
const a = 5;
export default 5;
---------------------------------// file2.js
import myA from './file1'; // myA from file2 = a from file1

However you can only have one default export per file.

2) Named import — export

// file1.js
export const a = 5;
------------------------------// file2.js
import { a } from './file1';
// notice the use of curly brackets

Unlike with default export, you can declare any number of named exports in a single file. However in the other file you will need to specify the exact same name inside curly brackets.

You can also mix both types of export in one single import, for example a very commonly used import in React:

import React, { Component, PropTypes } from ‘react’;

Here React is the default export and Component and PropTypes are named exports. In general you want to default export the main “thing” and named export smaller ones.

To understand it further, if you only import React, in order to access its Component class you will need to write React.Component. However if you import Component too, you will be able to just write Component:

import React from 'react';class Counter extends React.Component {
.....
}
------------------------------import React, { Component } from 'react';class Counter extends Component {
.....
}

Finally, you might also have seen this sentence when importing a module:

var React = require(‘react’);

Or this another one when exporting:

export.modules = { var a = 5 };

At a basic level, they are the same than our previous examples. The difference is the first ones being the ES6 versions of the second ones (Babel-loader will do the translations for us).

More about import and export.

Arrow functions

They will make our life much easier. The three things most important to keep in mind about them are:

1) They make code more compact

// Standard React Component
class HelloWorld extends React.Component {
render() {
return (<p>Hello World</p>);
}
}
-------------------------------------// Stateless React Component
const HelloWord = () => {
return (<p>Hello World</p>);
}

// Notice simpler declaration and no render() function needed.

2) They have implicit return

// Standar filter function
const
filtered = array.filter(function(element) {
return
element.value == 10;
}
-------------------------------------// Arrow function + implicit return
const filtered = array.filter((element) => element.value == 10);
// Wow// You can even remove parentheses when there is a single argument
const filtered = array.filter(element => element.value == 10);
// Much wow// Note: we can only use implicit return when we return one single // value.

3) They don’t rebind value of this keyword

// To alert a props.name value we would normally do
handleClick() {
alert( {this.props.name} );
}
render() {
return (
<button onClick={this.handleClick.bind(this)}>Click me</button>
);
}
-------------------------------------// We don't need to bind this value if we use an arrow function
const handleClick = () => {
alert( {this.props.name} );
}
render() {
return (
<button onClick={this.handleClick}>Click me</button>
);
}
// this is huge *best joke ever*

More about this keyword.

More about arrow functions.

Fonts and Webpack

I eventually came across a problem with fonts.

In CSS you can use custom fonts like:

#container {
font-family: MyFontName;
}
@font-face {
font-family: MyFontName;
src: url('pathto/MyFont.ttf');
}

However when you later run

webpack

to create your bundle file, fonts aren’t included.

So here are the 2 simple steps to solve it:

1) Install file-loader package from npm

npm install file-loader --save-dev

2) Add a font definition in the loaders of package.json

module: {
loaders: [
....
// Font Definitions
{
test:
/\.(ttf|otf|eot|svg|woff(2)?)(\?[a-z0-9=&.]+)?$/,
loader : 'file-loader'
}
]
}

This way, after creating the bundle, one file per font will be generated with a name like “0dcbbaa701328a3c262cfd45869e351f.ttf”. You will need to keep those files for deployment.

More about it in file-loader Github repository.

React-rating-system

Finally, but not less important, I did a second open source React Component.

The classical “5 stars rating”.

I started it during a train travel between Málaga and Madrid (2h30m) and when I arrived I had a working prototype of it:

  • While moving from left to right the stars would fill showing what rating you are going to give clicking on the current star.
  • Clicking on a star would print on screen the value of the rating given.
  • You could pass as prop an initial value (even decimal values) to show current rating of the product/something. For example a value of 3.6 would fill 3 stars at 100% and the fourth one would be filled at 60%.

The component was already usable, but as I wanted to share it I had to add some extra features and abstract everything (remember you always need to balance the ROI Return Of Inversion” of doing so).

So I wrote down a list of features that seemed mandatory and completed it by adding some features that similar Components found on npm had.

The final list was:

  • Support all kind of images (not only stars, but hearts, or circles).
  • Be able to pass the filling color as prop.
  • Be able to pass the onClick callback function as prop.
  • Set a bool prop to enable interactivity or not (for example when an user is not logged you might want to just display a rating and keep the Component unaffected by inputs).
  • When the mouse leaves it should back to its initial value
  • Except if you set a bool prop to lock rating on click.
  • Be able so pass the number of stars to display as prop.
  • If initial value prop is typo higher than maximum possible convert it to max value.

You can check the final result in this demo.

Or check the Github repository :)

Looking back, it was a good practice for 4 reasons:

  1. The iteration over the code (that seemed ugly for me) allowed me to improve clarity a lot and learn more about Stateless components and better organizing code (the source code is still kind of ugly though).
  2. Learnt about If-else in JSX, but I finally decided to not use it as it was not very clean in my opinion.
  3. I got better at abstracting Components.
  4. And of course, practice makes master.

And that’s everything for this chapter! I hope you found it useful and make sure to press the heart button and tweet about it, it helps a lot ! :) Thank you.

I have updated our React environment set up step-by-step guide with the fonts support.

In next chapter I will talk about my future with React (another month has passed already) and how I jumped to another technologies that complement very well React evironment.

Follow me to don’t miss it !

Have a nice day

Giveaway: if you have reached the end and you want to write cleaner ES6 JavaScript, check Airbnb JavaScript style guide.

Author

Enzo Ferey, developer and ReactJS lover
Eating, always eating.
www.enzoferey.com

--

--

Enzo Ferey

Learning to be the developer you want to work with | React.js lover | Maker | www.enzoferey.com