Basics of React

  • Basics of React
  • Basics of Webpack
  • npm and SemVer

In this section, we go over the basics npm and React and some of its syntactical quirks and install some necessary dependencies to be able to handle ES2015, 2016, and 2017 syntax, as well as jsx.

What is React?

React is a JavaScript library built by Facebook for highly efficient DOM rendering and a more functional programming approach to the frontend. From the React docs:

We built React to solve one problem: building large applications with data that changes over time.

Rather than use a markup language such as HTML, each React component is a function, so you can build the elements within your DOM using a much more powerful language: JavaScript.

And because each component is encapsulated in a function, you can reuse code, run tests, and build better abstractions much more easily.

There are a few React competitors that are formidable and arguably better. Among them are Cycle.js, Elm, and Om. Each has its advantages.

The reason we are using React is because it has a much larger community, it is easier to hire developers who know React, and it is supported by Facebook, which makes it more likely to have long-term staying power.

Since React v0.14.0, the main React function has been split into React and ReactDOM; ReactDOM is what we use to render our components to the DOM and React is what we use to create our components.

Most people use React.createClass to create components and ReactDOM.render to render our components to the DOM. Most people also use the JSX syntax, which mimics HTML's syntax. A very simple React app looks like this:

import React from "react"
import ReactDOM from "react-dom"
const App = React.createClass({
render() {
return <div>Hello World!</div>
},
})
ReactDOM.render(<App />, document.body)

There are those who prefer to use a different syntax for creating React components. That syntax extends the Component export from React. Both are perfectly valid.

We will be using the class syntax, as it is the syntax that Facebook suggests going forward. For a good article that explains the differences between the two, check out this article by Todd Motto. An example of this syntax would be:

import React from "react"
import ReactDOM from "react-dom"
class App extends React.Component {
render() {
return <div>Hello World!</div>
}
}
ReactDOM.render(<App />, document.body)

Another option (though slightly different), and one that we will be using on occasion, is to create your React components as a pure function, also referred to as a "stateless function", or a "presentational component".

import React from "react"
import ReactDOM from "react-dom"
const App = () => {
return <div>Hello World!</div>
}
ReactDOM.render(<App />, document.body)

Pure functions are highly performant with React, and since we are using Redux to handle state, many of our components will be pure functions. This is the case because our data is all passed down from the highest-level component, so none of our child components need to worry about their local state. We will cover these concepts in greater detail in the Redux section.

Also worth noting, if you want to pass props into one of these functions, you must pass it in through the function: const App = (props) => { ...

This should look familiar to people who have used the PureRenderMixin. Both rely on pure functions and give a nice performance boost. Just keep in mind that mixins are not supported by ES6 classes and are slowly being phased out.

When using Webpack, you will want to export these components so you can import them in other files. There are two options when it comes to exporting: default exports and named exports.

Each file can only have one default export, and we will primarily use default export.

import React from "react"
import ReactDOM from "react-dom"
class App extends React.Component {
render() {
return <div>Hello World!</div>
}
}
export default App

If you then wanted access to this component in a different file, you would simply import it the same way you imported React and ReactDOM, using the path to the file:

import React from "react"
import ReactDOM from "react-dom"
import App from "path/to"
...

So if your component lived within app/components, you would import it from that directory.

Named exports are slightly different, and you can export several named exports in a single file. The syntax for a named export uses curly braces for the import to pull out a specifically named pieces from within a module: import { Component } from 'react'. You can export functions, objects, classes, and other such things. For more information on exporting modules, check out this link.

You will also see examples where we don't name the actual file being imported and simple leave it at the directory name. This is only possible if you name the file index.js with a default export. Webpack will assume that the index.js file is the file you were looking for.

For example, if the path were app/Home/index.js, you could simply import from app/Home and Webpack will assume that you meant to import from index.js.

What is Webpack?

Webpack is a module bundler. If you've ever used Browserify and/or RequireJS, the concept is very similar but Webpack allows for much greater functionality.

This added functionality comes at the cost of simplicity. Finding oneself stuck in Webpack configuration hell is a not-so-uncommon experience for developers who have used it. That said, the advantages of webpack outweigh the pain of added upfront configuration.

Webpack is the technology that gives us the ability to split our app into modules that we can piece together to make our frontent efficient and well organized.

It also gives us a bunch of loaders which allows Webpack to replace your traditional build tool, such as Grunt or Gulp. We will go over all of this in greater detail as it becomes relevant, so if this is at all confusing, just know that Webpack is awesome, almost everyone uses it for their React projects, and we will be using it for this app.

Webpack is also where even the most advanced developer can find himself stuck in Webpack configuration hell for hours on end. So if you find yourself stuck on Webpack, know that you are not alone.

Setting up our frontend

We're going to change a few things in our newly-generated package.json file. We're going to add a start command so we can start our server with additional configuration using the command npm start. We can do this by changing the scripts in our package.json file:

"scripts": {
"start": "node server.js",
"test": "echo \"Error: no test specified\" && exit 1"
},

What we are doing here is telling Node to use the server.js file, which we will create shortly, to start our server. This allows us to keep all of our basic server configuration in one file and is common practice.

We are going to leave test alone for now. At the moment, if you run the command npm test, you will simply receive a message letting you know that it has not been set up yet.

Something that is worth noting about these scripts is that there are some commands that NPM handles by default. These include npm start, npm test, and a few others. If you want to run a custom script that is not supported by default (which we will do later on), you must use npm run <name of script>, with the name of your script in the appropriate field. You will see this in action later.

The next thing we want to do is set up a few dependencies so we can quickly get this project up and running. These dependencies are split into devDependencies and dependencies.

Development dependencies (devDependencies) will not be run in production, so this is where you put things like your module bundler (Webpack) and transpilers (Babel). Basically, anything that is processed before going into production goes here.

Your production dependencies (dependencies) are anything that you need to run your app after compilation. React is an example of a dependency that you will need when your app is live, because your app depends on React to render the frontend.

Add the following dependencies, each of which will be elaborated upon after the codeblock (note that a \ denotes a line break in your terminal):

$ npm install --save-dev babel-core babel-loader \
babel-preset-es2015 babel-preset-react babel-preset-stage-0

When adding packages to your app, you have the option of adding them to the package.json file and running npm install, which will install the dependencies you added, or running the command in your terminal.

It is also important to use the --save or --save-dev flag. If you do not, your app will run locally but when someone clones your repository or when you try to deploy, your app will not work because it will not know which dependencies to install.

After running the command above, you should see the following dependencies in your package.json file automatically added (though the version numbers will likely be different since these packages are updated constantly). You can also specify version numbers with the @ syntax: npm install --save-dev babel-core@6.7.6.

SemVer

Another thing that sometimes confuses people is the caret (^) that comes before the version number. This is for use in packages that abide by (as all packages should) SemVer, which stands for "semantic versioning". SemVer is very important for maintaining project stability and it is definitely worth checking out the docs to learn more about it.

The short version is that versioning should follow a pattern, and that the pattern actually means something. For example, X.Y.Z denotes X = major version, Y = minor version, Z = patch. Any changes in X will likely break your app, changes in Y will add new features but shouldn't break anything, and Z is for small patches and bug fixes that won't break anything.

So coming back to the caret (^) and using the example ^6.14.0, this tells npm that we want to use any package that is major version 6 and any minor version that is at least 14 (i.e. 6.15.2 would be fine). You might also see a tilde (~), which denotes a minor version. So for the same version above, it would tell npm to use anything with major version 6, minor version 14, and any acceptable patch (i.e. 6.14.3 would be fine). You can also use x in place of the version you want updated (i.e. 6.x.x is equal to ^6.14.0).

...
"devDependencies": {
"babel-core": "^6.14.0",
"babel-loader": "^6.2.5",
"babel-preset-es2015": "^6.14.0",
"babel-preset-react": "^6.11.1",
"babel-preset-stage-0": "^6.5.0"
}

The first dependency we add is babel-core. This is something you have to add to use babel-loader, which is really what we want. Why the two are separated, I have no idea, but I'm sure there is a perfectly good reason.

The second dependency is babel-loader. This is probably a good time to go over what loaders are and why they are a very useful part of Webpack.

Loaders

Loaders allow you to take code of a particular type and apply transformations to it. Or as it says in the Webpack docs:

Loaders allow you to preprocess files as you require() or "load" them. Loaders are kind of like "tasks" are in other build tools, and provide a powerful way to handle frontend build steps. Loaders can transform files from a different language like, CoffeeScript to JavaScript, or inline images as data URLs. Loaders even allow you to do things like require() css files right in your JavaScript!

One cool feature of loaders is that you can chain them to apply multiple transformations. For example, if you had a .less that had styles you wanted to apply to your component, you could run the less-loader, followed by the css-loader (because the less-loader transformed it into css), followed by the style-loader, which loads the style into your React component:

require("style-loader!css-loader!less-loader!./styles.less")

We'll cover the specifics of each loader we use as we progress through this course.

Back to setting up the frontend

The next three dependencies are babel-preset-react, babel-preset-es2015, and babel-preset-stage-0. These give you access to all the Babel plugins under that category. So, when you add the babel-preset-react plugin, you get access to the plugins:

  • react-constant-elements
  • react-display-name
  • react-inline-elements
  • react-jsx
  • react-jsx-compat

The last dependency we add is babel-preset-stage-0, which tells Babel to use the most recent experimental version of Babel. The stages range from 0 to 4, with 0 being the least stable and 4 being the most stable. We are going to use stage-0 because it gives us access to a lot of handy features that are not yet implemented in ES6, such as destructuring assignment and spread operators. We will explain what each feature is in more detail as we use them.

As of Babel 6, you need to be more explicit about what Babel uses. To do this, you have two options: create a .babelrc file, or add a babel configuration option within package.json. This is entirely a matter of preference, but since in this case we don't have many options to configure, let's just add it to package.json:

...
"devDependencies": {
...
},
"babel": {
"presets": ["es2015", "react", "stage-0"]
}

Then let's go ahead and add Webpack as a development dependency. We will add both Webpack and the the Webpack development server so we don't have to continually refresh the page to see the changes we made:

$ npm install --save-dev webpack@1.x webpack-dev-server@1.x

The last dependency we need before we can render "Hello World!" to our DOM is React. Let's go ahead and add React as a dependency for our app. Recall that this is not a development dependency, but a production dependency. Since we're building this app into static assets, it actually doesn't matter if you install things as devDependencies or dependencies, but it's generally advisable to keep modules that are exclusively for testing etc separate from things that your app actually depends on in runtime.

$ npm install --save react react-dom

In version 0.14.0, React split into two main pieces: React and ReactDOM. ReactDOM handles everything DOM-related, such as rendering to the DOM, while React itself handles the creation of all of your components. If this does not makes sense now, it will become immediately obvious as soon as we start using them.

In the 15.0.0 update, they changed their versioning to major versioning in accordance with SemVer mostly because corporate people were afraid to use software that "isn't even 1.0 yet". There are few, if any, breaking changes that will affect most applications.

Previous: Directory StructureNext: Basics of Webpack