React is a popular and in-demand front-end JavaScript web framework created by Facebook. It creates very responsive (meaning quick) web applications which do not require a full page reload to update the data. Thus, it can give the impression of using a desktop application rather than one based in a browser. These web apps can be either single or multi-page. React’s nearest competitor is Angular which is backed by Google.

It is used by many influential companies like Facebook, of course, as well as Airbnb, Disqus, Fiverr, Instagram, Netflix, Uber, and Udacity.

This post covers an introduction to React and shows a project which creates a template for a portfolio website. The post is a work in progress as it is a full application and will be updated as it is built.

React Overview

React comes with many features built-in as is typical with most web-based frameworks like routing, and authentication. Since it is a front-end framework there are also features for animations and styling.

Tools and Third-Party Packages

There are several tools that work well with React like Webpack and Redux. Webpack helps with module management and Redux is for managing state. Webpack is integrated with the React CLI and the settings can be changed by ejecting the project to show the configuration files. This is necessary, for instance, when using CSS Modules.

There are other notable projects that are built on React like React Native, Next.js, and Gatsby.js. React Native produces native mobile apps on Android and iOS. Next.js solves the problem of server-side rendering common to Single Page Applications so pages can be prerendered on the server for SEO. Gatsby.js is similar to static site generators like Jekyll (the platform for this blog).

There are also other third-party packages such as CSS Modules as mentioned above (for scoped CSS) and Radium (for media queries and pseudo selectors) which add additional functionality.

How React Updates the DOM

React uses 2 virtual DOMs, an old one and a rerendered one. They are representations in JavaScript. This is used because updating the real DOM is time-consuming. When render() is called (that is, when the state changes), React compares the old DOM with the rerendered one and updates the real DOM where the virtual DOMs differ.

 Create a React App

The CLI tool

The CLI tool (this refers to the command line interface tool) makes it easy to get started with building a React application. It comes with a development server and sets up the files needed to get a project going. This is very similar to the Angular CLI.

To install it, Node.js is needed first. Then run the following line from the command line to install the CLI globally.

npm install -g create-react-app

Starting a Project

To use the CLI tool, open a Terminal window and enter:

create-react-app portfolio-site

The last part can be anything and refers to the name of the folder that will be created to contain the starter code generated by the CLI. In this case it is portfolio-site This can take a while to generate as there are many node modules needed for development which are installed such as those for Babel, ES6, Webpack, and Watchman.

Following the instructions at the end of the Terminal output window, cd into the portfolio-site directory. Then use npm start to start the development server.

cd portfolio-site
npm start

Then, navigate to the URL displayed in the screen. The second address can be used from any other device on a WiFi network. This is great for testing responsive elements on other devices.

  Local:            http://localhost:3000/
  On Your Network:  http://192.168.0.6:3000/
 

The following screen should appear. Great! That’s your first React app.

react landing

The File Structure

To explore the file structure, open the portfolio-site directory in your favorite editor. Here I am using Visual Studio Code. Opening the folder reveals that there are 3 sub-directories (node_modules, public and src) and a few other files.

folder structure

node_modules

The node_modules directory holds a long list of modules for developing and running the app. This is where the dependent modules mentioned before like Babel and Webpack are kept.

public

The public folder has the favicon which displays in the browser tab when running the app. It also has the index.html template which loads in the browser and frames the components.

src

In the src folder are the App.js and App.css files. App.js contains the main component of the application. It is where most of the interesting parts of the application are happening. App.css is styling those elements. index.js is registering this component in App.js to render it in the index.html template. logo.svg contains the SVG code drawing the blue React logo (above). The CSS in App.css is making the logo rotate.

misc

The .gitignore file lists the files that should not be tracked by git if using git for version control. These include the node modules and the files used for production.

Project Overview and Planning

Wireframe

It’s always clarifying to start with a mock-up of what you will be building. A wireframe is a great way to do this. A Sharpie on dotted paper works well to get a rough draft of app ideas. The reasoning behind using the Sharpie is so that you don’t pay too much attention to details, only on the overall structure and necessary components. It’s fine if the ideas change further on. It’s not very pretty, but it does the job.

Below is a draft of the desktop and mobile UI. The big crosses inside circles or squares/rectangles represent images. The rest should be fairly explanatory.

ui wireframe portfolio

Application Structure and Features

Here, I envision a single-page application with a navigation bar and a jumbotron at the top. There are panels moving down the page representing services, portfolio samples, a blog, a contact form and a footer. The middle 3 panels can expand at the bottom to reveal more information about a particular service, project or blog post.

A recommender system can be used to recommend blog posts and portfolio samples. It would also be useful in the case of a store component which recommends products.

In the mobile version, the wider elements are collapsed underneath each other to take up the width of the screen.

There can be additional features which make use of React’s capabilities such as markers to like projects or remove ones which are not of interest as well as bookmarks for the blog posts.

A CSS Framework like Bootstrap can be used to make the design mobile friendly. Also, the data for the components can come in from a REST API built in Node.js or Django.

A Comp

Normally, at this step, the a comp is created by a designer. A comp is usually created in Sketch or Photoshop. It builds the UI up with more detail with and media needed like images, font styles, sizes and visual hierarchy, color schemes, logos, exact element spacing (including vertical rhythm) etc. This way the UI can be implemented in JavaScript, HTML, and CSS by a developer who has access all the design resources.

Understanding React Components

At the core of React are components. Components are the building blocks of any application. They can be thought of as custom HTML elements that can be used to create an application. They are not actually HTML though, but JSX (more on this below) which is transpiled to JavaScript by Babel in the end. Larger components may have sub-components creating a hierarchical tree-like structure for the application with the app.js component at the root.

In the above example, for instance, all the major panels (the navigation, jumbotron, services, portfolio, blog, contact) can be considered components and their content sub-components (the contained elements like the block per service or the block for one blog post).

The great thing about these components is that they are reusable. So, if the basic layout is the same and only the specific properties of the components change, these components do not have to be rebuilt. These different properties can be fed in instead.

State

Components come in two types: stateful and stateless. Stateful components are known as containers. Most components should be stateless. The stateful ones are more complex and make the application more unpredictable. Redux helps manage this problem (see below).

State objects can only be accessed in stateful or class-based components. The important point to note about these objects is that if they change, the render() life cycle hook will be called and the DOM will be rerendered.

Another difference between stateful and stateless components is that custom functions can only be added to the stateful components. This also means that event handlers and life cycle hooks like ComponentDidMount() can only be used in stateful components.

Redux

Redux is an independent module from React though they are often paired. It helps manage the complexity which arises when needing to manage state, especially in larger applications.

Without Redux, the state has to be passed between different components with routing query parameters. For this to happen, the entire hierarchy has to be traversed to reach from one component back up to the main App.js component then back down to the second component.

Instead, Redux keeps a central store with the application state. It works via a subscription model where a component subscribes to changes in state in the central store. Components dispatch actions. These actions go through a reducer which updates the store. The reducer is a function which receives the action and the old state as input and produces a new state which goes to the central store.

A Stateful (Class-Based) Component Example

In the App.js file (reproduced below) there is an example of a stateful component. Stateful components are built as a class which extends the Component class. This is why we need to import that class from the react library with import React, { Component } from 'react';. By contrast, stateless components are built with functions. The App component is at the root of the application and is rendered by the index.js file.

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <header className="App-header">
          <img src={logo} className="App-logo" alt="logo" />
          <h1 className="App-title">Welcome to React</h1>
        </header>
        <p className="App-intro">
          To get started, edit <code>src/App.js</code> and save to reload.
        </p>
      </div>
    );
  }
}

export default App;
JSX

The component is built with JSX. JSX is the markup being returned which looks similar to HTML. This is not actually HTML though. A clear indicator that this is not basic HTML is the className attribute which is used in place of the ordinary CSS class attribute because class is a keyword which is already being used in JavaScript.

The JSX code is transpiled by Babel into JavaScript. When transpiled, the code for a div which outputs plain text with a class of App on the div, for instance, becomes React.createElement('div', {className: 'App'}, 'Text output'). This is another reason the line import React, { Component } from 'react'; is needed as createElement() is called from the React object.

To put the text in an h1 tag, yet another call to React.createElement() is needed as shown below. Compared to JSX, this syntax can become very unwieldy very quickly, so it’s better to use JSX.

class App extends Component {
  render() {
    return React.createElement('div', {className: 'App'}, React.createElement('h1', null, 'Text Output'))
  }
}

JSX can look at bit odd at first especially when you are used to separating the markup from the JavaScript. It certainly was for me. Note that only one enclosing outer tag can be used in the return statement or an error will be produced.

These class-based components have to be exported at the end of the file. In this case this is done with export default App;.

A Stateless/Functional Component Example

In its simplest form, a component is a function that returns JSX. ES6 arrow functions are the recommended way to create components. An example is shown below.

import React from 'react';

const jumbotron = () => {
    return (
        <div>
            <h1>Jumbotron</h1>
            <h2>Subtext</h2>
        </div>
    )
}

export default jumbotron;

React Dev Tools

React gives very clear error messages in the console and in the browser when things go wrong. An example is shown below where an asset import is not available. This error is echoed in the Terminal where the server is running.

React Browser Error

An additional tool for debugging is the React Developer Tools add-on for chrome. This can be found in the Chrome Web Store.

react developer tools

The tab will appear to the right of the developer tools panel when it is installed and a React app is running in the browser tab. Right click on the page in Chrome and click Inspect to open the developer tools. The option of changing the theme is built-in.

react developer tools

Editing and Further Understanding App.js

Adding Inline Styles

The styles for the App.js file are being imported from App.js via import './App.css';. To add inline styles, use the syntax: style={{background:'#444'}} with two curly braces and the style in regular CSS syntax between. Note this is not really CSS, it is actually JavaScript. Thus if the CSS property is of the form similar to background-color it must be written as backgroundColor as below.

<h1 className="App-title" style={{backgroundColor:'#444'}}>Welcome to React</h1>

Editing App.css

The styling can also be adjusted via the App.css file. In the output below further changes are added. The background color in .App-header is altered from background-color: #222; to background-color: rgb(240, 101, 147);. Then, the height of the same class is changed from height: 120px; to height: 150px;. Finally, the height for .App-logo is changed from height: 80px; to height: 120px;. All the regular CSS property names can be used in this file.

react developer tools

Conclusion

This concludes part one of this series. We covered a fair amount of ground including an overview of React (who’s using it, related tools and the virtual DOM). Next, we created an app using the convenient and efficient React CLI tool.

Then, we planned the app with 2 wireframes and looked deeper into React components, state, and JSX, all essential parts of understanding how to use React. We also considered dev tools for debugging. Finally, we concluded with some editing of App.js to get a feel for building an app with React.

In the next steps, we start planning the component structure and building the app.

 References

  1. Schwarzmüller, Maximilian. React 16 – The Complete Guide (incl. React Router 4 and Redux). Udemy, https://www.udemy.com/react-the-complete-guide-incl-redux/learn/v4/overview.