Author avatar

Chris Parker

Understanding the Workflow to Build a React App

Chris Parker

  • Jan 10, 2020
  • 13 Min read
  • 648 Views
  • Jan 10, 2020
  • 13 Min read
  • 648 Views
Web Development
React

Introduction

React is a JavaScript library that is open-source and used to develop user interfaces. In this guide, we'll get an understanding of the steps to create a React app and understand the directory structure (files/folders) that gets generated by the Create React App tool. When we are developing a web app based on React, it requires an extensive workflow irrespective of whether we are developing a single-page or multi-page app.

Why Follow This Workflow

Following are some of the important reasons we need to follow the workflow:

• We need to have our code optimized. It is important for an app developed in React to have an optimized code with small size to enhance the performance of the app.

• Utilizing the latest features from JavaScript is another important reason to have the React build workflow. JavaScript is evolving continuously and there are times when there is a new feature available, but the browsers are not ready to support that particular feature. It can be helpful to have a tool that transpiles the code from the app to a code that can be easily understood by the browser, e.g., Babel transpiler.

• Another important reason is related to productivity. The auto-prefixing in CSS is amongst the newest features of JavaScript that helps in achieving maximum support for CSS features in various browsers. It would require great effort if these were added manually.

• Also, in terms of productivity, we can use a linter tool. Having a linter tool in our IDE saves us a lot of time by highlighting an error even before the compilation and execution of the code. The following code shows the working for a linter. We can see the error shown below the code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
import React from "react";
import logo from "./logo.svg";
import "./App.css";
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noreferrer noopener"
        >
          Learn React
        </a>
      </header>
    </div>
  );
);
export default App;
// Error 
23:1 error Parsing error: Unexpected token 21 | </div> 22 | ); > 23 | ); | ^ 24 | export default App;
// Error
javascript

How to Compose

The reasons to have React build workflow have been discussed above. Now, the next step is to understand how we can achieve it.

• Having a dependency management tool is the foremost thing. These are libraries provided by third parties. React, React DOM and almost all the build tools that we are going to use are dependencies. Node's Package Manager, also known as NPM, is an essential build tool for package and dependency management.

• Other than a dependency management tool, we can use a bundler to generate modular code. If the code is modular, it will have multiple files containing code for different parts of the app performing their own functionality. Webpack, for example, is a bundler that is very useful when we need to send split files to the browser. Some of the browsers do not support multiple files and even if they do, we cannot actually send multiple requests for these files.

• Finally, a server is required to run and test the code on our local computer.

Some of these can be very confusing for a beginner. But luckily, there is tool developed by the React team to create apps that support all the points we discussed above, and we do not need to configure anything manually. That special tool is Create React App. It is important to note that you should leave the NPM server running so that all the changes in the code can be observed immediately. It is important to discuss some of the main files and folders.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
.
├── node_modules
├── public
│   ├── favicon.ico
│   ├── index.html
│   └── manifest.json
├── README.md
├── src
│   ├── App.css
│   ├── App.js
│   ├── App.test.js
│   ├── index.css
│   ├── index.js
│   ├── logo.svg
│   └── registerServiceWorker.js
├── package.json
├── package-lock.json
├── README.md
javascript

The ‘package.json’ file contains all the dependencies of the project.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
{
  "name": "my-react-app",
  "version": "1.0.0",
  "private": true,
  "dependencies": {
    "react": "^16.8.6",
    "react-dom": "^16.8.6",
    "react-scripts": "3.0.1"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": "react-app"
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 2 Chrome version",
      "last 3 Firefox version",
      "last 5 Safari version"
    ]
  }
}
javascript

It can be seen through the package.json file that our project has three dependencies. It can also be seen that we have imported React. The project is using:

• Latest version of React.

• React DOM, which it provides methods that are specific to DOM. Only the render method will be used from this module in index.js file for the purpose of rendering the application to the DOM.

• React Scripts, a package that contains scripts and configurations that fulfill the requirements for React build workflow and includes development server and latest JavaScript features.

• The node_modules folder: This is where all the dependencies as well as sub-dependencies of the app are located. Only three of the dependencies were discussed in the package.json file: React, React DOM, and React Scripts. Specifically, React Scripts has many other dependencies, which consist of all the build tools that compile our code and so on. It is important to note that nothing in the node_modules folder should be modified.

This is the root folder of our project, and our web server directly interacts with it. There is one important file present in this folder named index.html. It is the only HTML file in the project so far and contains a simple HTML page as shown below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <!--
      manifest.json provides metadata used 
		when your web app is installed on a
      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
    -->
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <!--
      Notice the use of 
		%PUBLIC_URL% in the tags above.
      It will be replaced with 
the URL of the `public` folder during the build.
      Only files inside the `public` folder 
can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with 
client-side routing and a non-root public URL.
      Learn how to configure 
a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable 
JavaScript to run this app.</noscript>
    <div id="root"></div>
    <!--
      This HTML file is a template.
      If you open it directly in the browser, 
you will see an empty page.
You can add webfonts, meta tags, 
or analytics to this file.
      The build step will place 
the bundled scripts into the <body> tag.
To begin the development, 
run `npm start` or `yarn start`.
      To create a production bundle, use `npm run build` or `yarn build`.
    -->
  </body>
</html>
html

The React build workflow will install the script files in the above file. We can add HTML code to this file, but it is recommended not to update it. There is an important div element with ID root that needs to be discussed here:

1
<div id=”root”> </div>
html

The significance of this div lies in the fact that our React app will get rendered to this div. CSS libraries and metatags can be imported in this HTML file. The manifest.json file looks like below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
  "short_name": "React App",
  "name": "Create React App Sample",
  "icons": [
    {
      "src": "favicon.ico",
      "sizes": "64x64 32x32 24x24 16x16",
      "type": "image/x-icon"
    }
  ],
  "start_url": ".",
  "display": "standalone",
  "theme_color": "#000000",
  "background_color": "#ffffff"
}
javascript

The information about the app is provided to the browser by this file. For instance, this file is essential for mobile browsers to facilitate the addition of a shortcut to the web app.

Another important folder is the src. It contains files with the actual React app that we are going to work on. The index.js file is inside this folder;:

1
2
3
4
5
6
7
8
9
10
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// To have our app work offline and have faster loading, we can change unregister() to register() below. 
// However, this has some pitfalls.
// We can get to know more about service workers at the following link; https://bit.ly/CRA-PWA
serviceWorker.unregister();
javascript

The root DOM element, i.e. element with id root in the HTML file, is accessed from this script.

1
ReactDOM.render(<App />, document.getElementById('root'));
javascript

As you might have noticed, the above code uses the render method to render the React app. There is also a reference to the App object, which is imported from the App file.

1
import App from './App';
javascript

There is no need to add the extension .js for the App file because it is automatically added by the React build workflow. Below is our App.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React from "react";
import logo from "./logo.svg";
import "./App.css";
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}
export default App;
javascript

Currently, App is the only React component that we have in our project. Below is the App.css;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
.App {
  text-align: center;
}
.App-logo {
  animation: App-logo-turn 5s linear 2s infinite alternate;
  height: 40vh;
  pointer-events: none;
}
.App-header {
  background-color: #efefef;
  min-height: 150vh;
  display: flex;
  flex-direction: row;
  align-items: left;
  justify-content: left;
  font-size: calc(10px + 3vh);
  color: white;
}
.App-link {
  color: #efefef;
}
@keyframes App-logo-turn {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(180deg);
  }
}
css

The styling of the app component in App.js is determined by the App.css file. However, the styles defined here do not apply only to the App component. These are actually global styles. There is also the index.css file as shown below:

1
2
3
4
5
6
7
8
9
10
body {
  margin: 0;
  font-family: "Times New Roman", Times, serif, Arial, sans-serif, Helvetica;
  -webkit-font-smoothing: auto;
  -moz-osx-font-smoothing: auto;
}
code {
  font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
    monospace;
}
css

The above CSS represents global styles. The registerServiceWorker.js file is important to register any service worker. It loads the script files of the project, but it is not necessary to add any configuration here. It can be deleted as well if we do not intend to use any service workers. Finally, we have the App.test.js file as below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import React from 'react';
import logo from './logo.svg';
import './App.css';
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}
export default App;
javascript

The purpose of the above code is to write test for various components of the app.

Conclusion

The purpose of this guide is to help every developer write code efficiently and to provide a suitable coding environment. When we are working on large-scale React apps, it is essential to have the build workflow to avoid any kind of manual work. It would be very difficult to develop React apps if we needed to remember so many tools just to get started. Fortunately, the Create React App tool has made our job easier.

4