• No results found

It is worth stressing that we always want to keep our components very small and our render methods very clean and simple.

However, that is not an easy goal, especially when you are creating an application iteratively and in the first iteration you are not sure exactly how to split the components into smaller ones.

So, what should we be doing when the render method becomes too big to maintain? One solution is to split it into smaller functions in a way that lets us keep all the logic in the same component.

Let's look at an example:

renderUserMenu() { // JSX for user menu }

renderAdminMenu() { // JSX for admin menu }

render() { return ( <div>

<h1>Welcome back!</h1>

{this.userExists && this.renderUserMenu()} {this.userIsAdmin && this.renderAdminMenu()} </div>

) }

This is not always considered a best practice because it seems more obvious to split the component into smaller ones. However, sometimes it helps just to keep the render method cleaner. For example, in the Redux realworld examples, a sub-render method is used to render the load more button.

Now that we are JSX power users, it is time to move on and see how to follow a style guide within our code to make it consistent.

ESLint

We always try to write the best code possible, but sometimes errors happen, and spending a few hours catching a bug due to a typo is very frustrating. Luckily, there are some tools that can help us check the correctness of our code as soon as we type it.

These tools are not able to tell us if our code is going to do what it supposed to do, but they can help us to avoid syntactical errors.

If you come from a static language such as C#, you are used to getting that kind of warning inside your IDE.

Douglas Crockford made linting popular in JavaScript with JSLint (initially released in 2002) a

few years ago; then we had JSHint and finally, the de-facto standard in the React world nowadays is ESLint.

ESLint is an open-source project released in 2013 that became popular thanks to the fact that it is highly configurable and extensible.

In the JavaScript ecosystem, where libraries and techniques change very quickly, it is crucial to have a tool that can be easily extended with plugins, and rules that can be enabled and disabled when needed.

Most importantly, nowadays we use transpilers such as Babel, and experimental features that are not part of the standard version of JavaScript, so we need to be able to tell our linter which rules we are following in our source files.

Not only does a linter help us to make fewer errors, or at least, find those errors sooner, but it enforces some common coding style guides, which is really important, especially in big teams with many developers, each one with their favorite coding style.

It is very hard to read the code in a code base where different files, or even various functions, are written using inconsistent styles.

Installation

First of all, we have to install ESLint as follows:

npm install --global eslint

Once the executable is installed, we can run it with the following command:

eslint source.js

The output will tell us if there are errors within the file.

When we install and run it for the first time, we do not see any errors because it is completely configurable and it does not come with any default rules.

Configuration

Let's start configuring it.

ESLint can be configured using a .eslintrc file that lives in the root folder of the project. To add some rules, we use the rules key.

For example, let's create a .eslintrc and disable the semicolon:

{

"rules": {

"semi": [2, "never"] }

}

This configuration file needs a bit of explanation: "semi" is the name of the rule and [2, "never"] is the value. It is not very intuitive the first time you see it.

ESLint rules have three levels, which determine the severity of the problem: off (or 0): The rule is disabled

warn (or 1): The rule is a warning error (or 2): The rule throws an error

We are using the value 2 because we want ESLint to throw an error every time our code does not follow the rule.

The second parameter tells ESLint that we want the semicolon never to be used (the opposite is always).

ESLint and its plugins are very well documented and for any single rule, you can find the description of the rule and some examples of when it passes and when it fails.

Now, create a file with the following content:

var foo = 'bar';

(Note that we are using var here because ESLint does not know yet that we want to write code in ES2015.)

If we run eslint index.js we get the following:

Extra semicolon (semi)

This is great; we set up the linter and it is helping us follow our first rule.

We can enable and disable every single rule manually, or we can enable the recommended configuration in one go by putting the following code into our .eslintrc:

{

"extends": "eslint:recommended" }

The extends key means that we are extending the recommended rules from the ESLint configuration, but we can always override single rules manually inside our .eslintrc using the rules key, as we have done before.

Once the recommended rules are enabled and we run ESLint again, we should not receive an error for the semicolon (which is not part of the recommended configuration), but we should see the linter complaining about the fact that the foo variable has been declared and never used.

The no-unused-vars rule is pretty useful for keeping our code clean.

As we have said since the beginning, we want to write ES2015 code, but changing the code to the following returns an error:

This is the error in question:

Parsing error: The keyword 'const' is reserved

So, to enable ES2015, we have to add a configuration option:

"parserOptions": { "ecmaVersion": 6, }

Once we have done this, we will get the unused error again, which is fine. Finally, to enable JSX, we use the following:

"parserOptions": { "ecmaVersion": 6, "ecmaFeatures": { "jsx": true } },

At this point, if you have written any React applications before and have never used a linter, a good exercise to learn the rules and get used to it is to run ESLint against the source and fix all the issues.

There are different ways in which we make ESLint help us write better code. One is what we have done until now: run it from the command line and get the list of errors.

This works, but it is not very convenient to run it manually all the time. It would be great to add the linting process inside our editor to get immediate feedback as soon as we type. To do that, there are ESLint plugins for SublimeText, Atom, and the other most popular editors.

In the real world, running ESLint manually or getting the feedback live in the editor, even if it is very useful, is not enough, because we can miss some warnings or errors, or we can simply ignore them.

To avoid having unlinted code in our repository, what we can do is to add ESLint at one point of our process. For example, we could run the linting at test time in a such way that if the code does not pass the linting rules, the whole test step fails.

Another solution is to add the linting before opening a pull request so that we have the chance to clean up the code before our colleagues start reviewing it.