© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
E. ElromReact and Librarieshttps://doi.org/10.1007/978-1-4842-6696-0_2

2. Starter React Project and Friends

Elad Elrom1  
(1)
Montvale, NJ, USA
 

In this chapter, we will be covering lots of libraries, and it might be overwhelming. However, I want to provide you with a great foundation so you can have the best startup project possible. The startup project will serve you well because you can copy and reuse the code for all the projects and examples we will be using in this book. This practice will make you a top-notch React developer who can tackle any size project that comes your way, as well as help you land your dream job. It will also speed up your development.

By the end of this chapter, you will have a starter project that includes many of the libraries we will be covering in this book. Let’s get started!

Getting Started with the Create-React-App Starter Project

In the previous chapter, we created a simple “Hello World” application from scratch, and we talked about how it works behind the scenes. We covered topics such as JSX, DOM, the React virtual DOM, Babel, ES5/ES6, and SPAs.

Creating a React app was easy and took just few lines of code. However, to create a real-life application based on one page (an SPA) with multiple views, many user gestures, lists with hundreds or thousands of items, member areas, and other common pieces that are common in today’s applications, there is much more we need to learn.

In this book, my goal is to set you up with a large toolbox full of the best libraries and tools so you can build a top-grade React application and get the most out of React. For that, we need to look at several popular libraries and tools in the world of React.

We could start from complete zero, but that’s not needed. As I mentioned in the previous chapter, Create-React-App (CRA) is the most popular starter project for a React web-based application. (See https://github.com/facebook/create-react-app.) It provides a boilerplate project, and you can be up and running quickly with many of the necessary tools and library that are standards when building a top-grade React application.

It includes vanilla-flavor packages and other more valuable packages. Additionally, CRA has an option to include templates with more sophisticated libraries, or you can create your own template that has certain elements that CRA does not include.

CRA has already made some decisions for us. For example, the build tool is a tool called Webpack over Rollup or Parcel. Task Runners is set up with NPM scripts over other tools such as Gulp. CSS, JS, and Jest are used as the defaults.

After working on and reviewing projects and libraries that help get the job done with React, it’s hard to stay neutral and not recommend certain tools, which is why I’ve chosen to use the tools in this chapter. In addition, since many libraries are not easy to migrate to, you’ll want to start on the right foot instead of switching tools later. That’s why we are setting up our project with the libraries in this library. These libraries will help you get the job done, and you can use the template for other projects, whether it’s a small project or a larger enterprise-level project.

React Developer Road Map

Becoming a true professional React developer is more than just knowing the React library. As we’ve mentioned, there are tools and libraries that can help expediate development because, remember, React is not a framework. React is a JavaScript library developed by Facebook to handle the user interface and nothing more.

To help figure out the pieces that will turn React into a full-blown framework that is capable of creating quality apps efficiently and that can compete with other JS frameworks, check out the road map in Figure 2-1.
../images/503823_1_En_2_Chapter/503823_1_En_2_Fig1_HTML.jpg
Figure 2-1

React developer road map (source: https://github.com/adam-golab/react-developer-roadmap)

This chart demonstrates the path that is recommended to become a top-notch professional React developer.

Do not get intimidated by this chart. If you follow this book, by the time this book is over, you will learn about many of these libraries and more and be able to tackle any size project.

How Can I Integrate These Tools into My ReactJS Project?

As I mentioned, CRA doesn’t include many of the tools that can help you tackle real-life React projects. However, I have set up a CRA template that will include all the must-know libraries. With one command, you can get the starter project that includes all the libraries needed. We will set that up shortly in this chapter.

Keep in mind that things change rapidly; plus, your project may need a different tool or you might want to experiment. That’s why in this section we’ll break it all down and show how to install each library.

In this section, we will be installing the following libraries:
  • Type checker: TypeScript

  • Preprocessors: Sass/SCSS

  • State management: Redux Toolkit/Recoil

  • CSS framework: Material-UI

  • Components: Styled Components

  • Router: React Router

  • Unit testing: Jest and Enzym + Sinon

  • E2E testing: Jest and Puppeteer

  • Linter: ESLint and Prettier

  • Other useful libraries: Lodash, Moment, Classnames, Serve, react-snap, React-Helmet, Analyzer Bundle

The list was React libraries. The folder structure is park of the what I will be covering but it’s not a library. We could add this sentence to explain the readers.

Prerequisites

You can install the libraries using NPM (https://www.npmjs.com/). You need Node.js to get NPM.

NPM and Node.js go hand in hand. NPM is the JavaScript package manager and the default package manager for the JavaScript Node.js environment.

Install Node and NPM on a Mac/PC

Node.js needs to be at least version 8.16.0 or 10.16.0. The reason we need that version is that we need to use NPX. NPX is the NPM task runner introduced in 2017, and it is used to set up CRA.

Install it if it’s missing by typing the following in the Terminal (Mac) or in Windows Terminal (Windows):
$ node -v
If it’s not installed, you can install it for both Mac and PC from here (see Figure 2-2):
https://nodejs.org/en/
../images/503823_1_En_2_Chapter/503823_1_En_2_Fig2_HTML.jpg
Figure 2-2

Nodejs.org

The installer recognizes your platform, so if you are on a PC, it’s the same steps.

Once you download the installer, run it. Once that’s complete, run the node command in Terminal, as shown here:
$ node -v

The command will output the Node.js version number.

Download the Libraries: Yarn or NPM

To download packages from the NPM repository, we have two options: Yarn or NPM. NPM is installed when we install Node.js. However, in this book, we will mostly use the Yarn library. We will be using Yarn as much as possible for downloading packages instead of NPM because Yarn is faster than NPM. Yarn caches the installed packages as well as installs packages simultaneously.

Install Yarn on a Mac/PC

To install Yarn on a Mac, use brew in the Terminal.
$ brew install yarn
Just like with Node.js, run yarn with the -v flag to output the version number.
$ yarn -v
On a PC, you can download the .msi download file from here:
https://classic.yarnpkg.com/latest.msi
You can find more installation options here:
https://classic.yarnpkg.com/en/docs/install/#mac-stable

Create-React-App MHL Template Project

Equipped with Node.js as well as NPM and Yarn, we are ready to get started. We can use the CRA Must-Have-Libraries (MHL) template project I created for you, and it will produce the final result of this chapter and include all the libraries we are setting up in this chapter.

You can get it from here:
https://github.com/EliEladElrom/cra-template-must-have-libraries

It’s good to have this template project as your starter library, not just because it is easy and includes all the libraries we need, but also because I will be able to update this starter project long after the book is released in case anything breaks or needs an update, as often happens with NPM libraries.

You can create the final project of this chapter using the CRA template with Yarn with one command, shown here:
$ yarn create react-app starter-project --template must-have-libraries
Or you can create it with NPX, as shown here:
$ npx create-react-app your-project-name --template must-have-libraries
To run this project, you can change directory to starter-project and run the start command in the Terminal, as shown here:
$ cd starter-project
$ yarn start

This command will install all the dependencies and start the project on a local server. You will learn more about what’s happening under the hood in the next section.

In the rest of this chapter, I will explain what this project includes and reverse engineer the project for you, so you can understand fully what is happening under the hood. It is not mandatory to do all the steps in this chapter as you already have the final project ready.

Vanilla-Flavor Create-React-App

Since you were able to install the starter template project, you can get started with development right away. It’s good to know each library that is installed so you fully understand what this project includes and can customize your project based on your exact needs. To create CRA without using the CRA MHL template project, you can install each library on our own. Just start a new CRA using the vanilla-flavor template by running the following command in Terminal with yarn:
$ yarn create react-app hello-cra
Keep in mind that the yarn command is equivalent to the following command using the NPM NPX task runner, just as we saw in the MHL template project:
$ npx create-react-app hello-cra
The first parameter is the library we are downloading. The third parameter’s hello-cra is our project name. Next, we need to change directory to our project.
$ cd hello-cra
Lastly, type the following command to start the project in the Terminal/Windows Terminal:
$ yarn start
With NPM, it is the same, as shown here:
$ npm start
We get this message in our Terminal:
Happy hacking!
Compiled successfully!
You can now view hello-cra in the browser.
  Local:            http://localhost:3000
  On Your Network:  http://192.168.2.101:3000

Note that the development build is not optimized. To create a production build, use yarn build.

Our app will open automatically on port 3000 using our default browser. If it doesn’t, you can use any browser and use this URL: http://localhost:3000/.

Note

If you want to stop the development server, use Ctrl+C.

What’s happening in the background is that the CRA app created a development server for us. See Figure 2-3.
../images/503823_1_En_2_Chapter/503823_1_En_2_Fig3_HTML.jpg
Figure 2-3

Vanilla CRA on port 3000 in our browser

Congratulations, you just created and published CRA on the development server! The React project includes all the libraries that come with CRA out of the box.

If you examine the code and files that were created for us (see Figure 2-4), you can see that there are many files that make up our single-page application. Examples include App.js and index.js. We also have style sheet files such as App.css and index.css.
../images/503823_1_En_2_Chapter/503823_1_En_2_Fig4_HTML.jpg
Figure 2-4

CRA files and folders

React was originally designed to be a SPA, and normally we would need to write a script to combine our files into one file or a chunk of files that we will need to include in our application for the code to be available. However, since we are using CRA, all of that is done for us automatically.

CRA uses Webpack and Babel to pack our files into a single index.html page and into files called bundle.js and *.chunk.js. It may generate other files as well as needed.

Note

CRA is using the Webpack module bundler out of the box. Webpack is an open source JavaScript bundler that uses loaders to bundle files and create static assets.

When we type the command yarn start, the script initiates an NPM script that creates a development environment for us. The script caches our files in memory and serves them when we navigate to the URL.

Take a look at Figure 2-5, which illustrates this process.
../images/503823_1_En_2_Chapter/503823_1_En_2_Fig5_HTML.jpg
Figure 2-5

10,000-foot view to illustrate CRA using Webpack and Babel to pack our files into a single index.html page

To view the application’s source code and check the files created for us, go to this URL on Chrome: http://localhost:3000/.

Or we can also inspect the HTML DOM elements with Chrome DevTools. On Chrome right-click and select Inspect to view the DOM tree.

You can see the following files in the body HTML tag:
<script src="/static/js/bundle.js"></script>
<script src="/static/js/0.chunk.js"></script>
<script src="/static/js/main.chunk.js"></script>

The bundle.js file, as the name suggests, bundles our JavaScript source code files into one file, and the *.chunk.js files bundle our styles into chunks of files. You can go to the URLs of these files to view the content.

The heavy lifting is done inside our project in a folder called node_modules that includes many libraries that are dependencies that our project is using. Take a look at Figure 2-6.
../images/503823_1_En_2_Chapter/503823_1_En_2_Fig6_HTML.jpg
Figure 2-6

node_modules folder with dependencies

You can find the list of the dependencies in the node_modules folder in a file called package.json, which is used by Node.js. The file contains information about our project such as the version, the libraries are using, and even the scripts Node.js will be running.

Open the package.json file. Notice that the list of library dependencies our project is using is short if you compare it to the long list in the node_modules folder (keep in mind the library versions are likely to change often after the book is released).
"dependencies": {
  "@testing-library/jest-dom": "^4.2.4",
  "@testing-library/react": "^9.3.2",
  "@testing-library/user-event": "^7.1.2",
  "react": "^16.13.1",
  "react-dom": "^16.13.1",
  "react-scripts": "3.4.3"

Each dependency holds the name of the library and a version number.

If we check our node_modules folder, it is full of other developers’ libraries. In fact, there are more than 1,000, and when we downloaded our CRA, it took a while (depending on your Internet speed, of course) to download the project.

That is because of all these dependencies. Where are all these dependencies coming from then?

Each library includes other dependencies or subdependencies, so although we don’t have these libraries listed in our project’s package.json file, they are listed in other libraries or sublibraries.

Also notice that there is a section in our package.json file that specify scripts.
"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "eject": "react-scripts eject"
}
In fact, when we were running yarn start, the process of creating our local server was happening. Where is that script coming from? To answer that, open the following library and look at the following code that builds our development server:
hello-cra/node_modules/react-scripts/scripts/start.js
react-scripts

These scripts are using a library called react-scripts . If you go to the hello-cra/node_modules/react-scripts/package.json file, you will see a long list of dependencies that the code is using to package files with Babel and Webpack and build our server. Each of these sublibraries will have other dependencies and so on.

That’s how six libraries end up as more than 1,000 in our node_modules folder.

Gitignore

It is common practice to create a .gitignore file in each project. That file can include files we want to exclude.

For instance, CRA already included a .gitignore file, and node_modules already listed it to be excluded. Then we ran the yarn command and checked the package.json file, which installed all these dependencies for us instead of including all these libraries with our project, which will make our project very large.

Public Folder

We also have a folder in our app called public that includes our application icon. Specifically, it contains the following:
  • public/favicon.ico, logo192.png, logo512.png: Icons used inside the manifest.json file

  • public/index.html: Our index page

  • public/manifest.json: Information about our application and styles

  • public/robots.txt: Instructions to search engines

If we check our index.html page, we see tokens that were set in the manifest.json file, but if we open the public/index.html file inside the HTML body tag, we don’t see any of the JS bundle chunks such as the *.chunk.js and bundle.js files that we saw when we inspected the code in the browser. Take a look:
public/index.html;
<body>
  <noscript>You need to enable JavaScript to run this app.</noscript>
  <div id="root"></div>
</body>

The reason is that the NPM scripts are generating our index file based on this file as well as the files it generates. If we wanted to publish our app to production, for example, we would run a different command (build instead of start), and different files would be generated. You will learn more about publishing to production as well as how to optimize the JS bundle chunks later in this book.

You can download the code from here:
https://github.com/Apress/react-and-libraries/tree/master/01/hello-cra
To have Yarn use the package.json file and download all the dependencies, run the following:
$ yarn start

Create-React-App with TypeScript

CRA comes in two flavors: vanilla (JS) and TypeScript. Notice that our application files src/public/App.js and src/public/index.js have .js file extensions, which means they are JavaScript files. CRA sets our project out of the box to JavaScript as the default setting.

However, when it comes to writing React code, there are two main options. We can write our code with JavaScript (JS) or with TypeScript (TS). The vanilla-flavor CRA you downloaded is set to JavaScript. However, we will be writing our code in this book using TypeScript, as we mentioned in the previous chapter.

CRA Template with TypeScript

To set up our project with TS using Yarn, the command is similar to how we set up CRA. The only difference is that we add the TS template for TypeScript created by the React community.
$ yarn create react-app starter-project --template TypeScript

We are using the --template flag with TS, and we name our project starter-project.

Now, change the directory to your project and start the project to ensure all went well, just as we did before.
$ cd starter-project
Tip

I recommend testing your project after each install to ensure it’s still running. Libraries and dependencies change often, and ensuring the project doesn’t break should be your first priority.

$ yarn start
The app should open on port 3000 just as we did it before: http://localhost:3000/. See Figure 2-7.
../images/503823_1_En_2_Chapter/503823_1_En_2_Fig7_HTML.jpg
Figure 2-7

CRA TS app running on port 3000

Notice that the copy changes on the app to src/App.tsx (from Figure 2-3), as well as that the files changed from .js to .tsx in our app.

Next, we need to add the following types for TS so that Webpack knows how to handle .tsx file types and bundle them and so they can be included as static assets in our project.
$ yarn add -D typescript @types/node @types/react @types/react-dom @types/jest @typescript-eslint/scope-manager

When using Yarn, we use the -D flag (which stands for developer “dependencies”) when we want to update our project’s package.json to include a library under devDependencies. The package.json file holds the project’s libraries.

Note

The types installed for TypeScript are used to provide TypeScript with type information about APIs that are written in JavaScript.

The types we just installed include TypeScript for Jest tests and ESLint. CRA comes bundled with Jest and Jest-dom to test our application. We will be learning about testing our application with Jest and ESlint later in this book, but I wanted you to be aware that we are setting up these types already.

In addition to changing our code files from .js to .ts, the template project also includes a file called tsconfig.json. This file holds a specific setting for the compiler that will compile our files from .tsx down to .js with information such as what we targeting such as ES6 and other settings.

CSS Preprocessors: Sass/SCSS

Cascading Style Sheets (CSS) is a core functionality in HTML, and you need to familiarize yourself with CSS if you are not already. This goes for working with HTML in particular and in React specifically. On large projects, CSS preprocessors are often used to complement CSS and add functionality. We will discuss these later in this book.

In terms of CSS preprocessors, there are four main CSS preprocessors that are often used with React projects: Sass/SCSS, PostCSS, Less, and Stylus.

Note

CSS is used to represent the visual layout of the web page on different devices. CSS preprocessors are used to enhance CSS functionality.

Sass/SCSS has the upper hand for the majority of today’s projects, so that’s what we will be using. In fact, Sass/SCSS is the most popular and will probably get you the best-paying job as a developer according to surveys (https://ashleynolan.co.uk/blog/frontend-tooling-survey-2019-results). If you want to see a comparison between the different CSS preprocessors, check out my article on Medium: http://shorturl.at/dJQT3.

We will be learning more about CSS and SCSS later in this book, but for now, install it with Yarn.
$ yarn add -D node-sass

Just like with CSS, if we want to use SCSS modules in TypeScript the same way we would use them in JavaScript, we need to install Webpack’s loader for Sass/SCSS. It’s called scss-loader.

Since we are using TS, we need a replacement for scss-loader that works with TS and generates typings for Sass/SCSS. Install the loader with Yarn.
$ yarn add -D scss-loader typings-for-scss-modules-loader

Redux Toolkit/Recoil

The Redux toolkit is the standard way to organize React app data and user interaction so your code doesn’t get messy.

Note

Redux is an open source JavaScript library for managing application state. It is most commonly used with React for building user interfaces. See https://redux.js.org.

We will be going over Redux and Redux Toolkit later in this book. For now, let’s install the Redux Toolkit libraries and types.
$ yarn add -D redux @reduxjs/toolkit react-redux @types/react-redux
Recoil is another state management library created by the Facebook team that I believe will take over Redux Toolkit. We will work with both of these libraries later in this chapter. To install Recoil, use this:
$ yarn add recoil@^0.0.13

Material-UI CSS Framework

A CSS framework (or CSS libraries) is based on the concept of bringing a more standardized practice to your web development. Using a CSS framework, you can speed up your web development effort versus just using CSS (or other style sheets) as it allows you to use predefined web elements.

Yes, we could create all of our custom components and style them, but most times it isn’t worth the effort, and besides writing the components, we would need to test them on all browsers and devices. Can you imagine?
import 'bootstrap/dist/css/bootstrap.css';

Both Bootstrap and Material-UI are great CSS frameworks in certain projects to get started right away, without spending hours creating your own components.

To install it, I will be setting up Material-UI core as well as the icons bundle.
$ yarn add -D @material-ui/core @material-ui/icons

To get Material-UI to work seamlessly with TS, we also need to update some settings in our tsconfig.json file so that the TS page on React doesn’t encounter any errors.

Open tsconfig.json with a text editor and update it.
// tsconfig.json
{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "es6", "dom",
      ...
      ...
    ],
    "noImplicitAny": true,
    "noImplicitThis": true,
    "strictNullChecks": true,

Styled Components

Styled Components go hand in hand with Material-UI. Styled Components is a styling solution, and it can also be used beyond Material-UI.

To add Styled Components and types to our project, use this:
$ yarn add -D styled-components @types/styled-components
Also keep this link handy, in case you need to install fonts:
https://medium.com/r/?url=https%3A%2F%2Fgithub.com%2Ffontsource%2Ffontsource

React Router

React is based on a single-page application; however, most applications need multiple views in React’s single-page application paradigm.

Building an application on a single component is not ideal as the code and complexity can grow and it can become a developer’s nightmare to maintain and test. We will learn more about creating components and subcomponents in the next chapter.

To handle routing, there are many tools to choose from: React Router, Router5, Redux-First Router, and Reach Router, to name a few.

The standard for React projects at the time of writing is React Router. To add React Router and types for Webpack, follow this command:
$ yarn add -D react-router-dom @types/react-router-dom

Jest and Enzyme + Sinon

Jest is a JavaScript unit testing framework and the standard for React applications. It was built to be used with any JavaScript project, and it comes with CRA out of the box. However, we do need Jest-dom and Enzyme to enhance the capabilities of Jest.

For Enzyme we want to install the React 16 adapter (that’s the latest version at the time of writing but likely to change to 17). Also, we need to install react-test-renderer so we can render React components to pure JavaScript objects without depending on the DOM or a native mobile environment. Later in the book, we will be using Jest’s snapshot testing feature to automatically save a copy of the JSON tree to a file and use tests to check that it hasn’t changed.

To install these tools, use this command:
$ yarn add -D enzyme enzyme-adapter-react-16 react-test-renderer
We also want to make our life easier by installing the enzyme-to-json library so our code will be simplified when we use these libraries later in the book.
$ yarn add -D enzyme-to-json

Sinon

Another must-have library that we should be aware of and add to our toolbox is Sinon (https://github.com/sinonjs/sinon). Here’s the command you can use to add it:
$ yarn add sinon @types/sinon

Jest and Sinon serve the same purpose, but there are times that you may find one framework more natural and easier to work with for the specific test. We will cover Sinon later in this book.

E2E Testing:  Jest and Puppeteer

Testing is at the core of delivering quality software. There is a hierarchy in testing, and E2E is usually only considered after unit testing and integration testing are done.

End-to-end testing (E2E testing) is a testing method that includes testing our app workflow from beginning to end. What we are doing in E2E is replicating real user scenarios so our app is validated for integration and data integrity.

The solutions for E2E testing are Jest and Puppeteer. Puppeteer is the most popular E2E solution, and it integrates with Jest. To get this started, use this:
$ yarn add puppeteer jest-puppeteer ts-jest
Don’t forget to also add the types for TS.
$ yarn add yarn add @types/puppeteer @types/expect-puppeteer @types/jest-environment-puppeteer

That’s all you need to get set up with Jest and Puppeteer and to configure everything and see an example of E2E testing for App.tsx. You’ll learn more about E2E later in the book.

Component Folder Structure

When you work on a React project and the code keeps growing in size, it can become overwhelming with the number of components you may have, and then it can be hard to find them.

A neat way to organize your components so it makes them easier to find is to split the components into a separated component type like in Figure 2-8.
../images/503823_1_En_2_Chapter/503823_1_En_2_Fig8_HTML.jpg
Figure 2-8

A suggested React folder structure for Redux and TS

This is my recommended folder structure to get started; however, feel free to use it as a suggestion only.

To follow this structure, create these folders:

  • src/components

  • src/features

  • src/layout

  • src/pages

  • src/redux

  • src/recoil/atoms

If you on a Mac, you can use this one-liner in the Terminal:
$ mkdir src/components src/features src/layout src/pages src/redux src/recoil/atoms

Generate Templates

As developers, we don’t like writing code again and again. generate-react-cli is a helpful utility we can use. It is based on templates, so we don’t need to write our code again and again.

If you come from Angular, you probably love the Angular CLI and that it can generate templates for your project.

You can generate your project templates using the generate-react-cli project in a similar way in React. To install, we will be using the NPX task script.
$ npx generate-react-cli component Header

Because it’s the first time running the script, it will install and create generate-react-cli.json with the options you chose the first time you used the tool, but feel free to change these manually.

A cool feature is that we can create our own template. Here is an example of creating a custom template for React pages.

Don’t dig into the template code at this time. We just set these templates, and we will be going over the code and what it means in the next chapter as we build our components.

Change generate-react-cli.json to point to the template files we will be creating.
{
  "usesTypeScript": true,
  "usesCssModule": false,
  "cssPreprocessor": "scss",
  "testLibrary": "Enzyme",
  "component": {
    "default": {
      "path": "src/components",
      "withStyle": true,
      "withTest": true,
      "withStory": false,
      "withLazy": false
    },
    "page": {
      "customTemplates": {
        "component": "templates/page/component.tsx",
        "style": "templates/page/style.scss",
        "test": "templates/page/test.tsx"
      },
      "path": "src/pages",
      "withLazy": false,
      "withStory": false,
      "withStyle": true,
      "withTest": true
    },
    "layout": {
      "customTemplates": {
        "component": "templates/component/component.tsx",
        "style": "templates/component/style.scss",
        "test": "templates/component/test.tsx"
      },
      "path": "src/layout",
      "withLazy": false,
      "withStory": false,
      "withStyle": true,
      "withTest": true
    }
  }
}
Create a template file for the TypeScript class page components with a React router and a hook to the pathname: templates/component/component.tsx. In the next chapter, we will create a custom React component, and this template component will make sense. You can change the author name to your own name and website, of course.
/*
Author: Eli Elad Elrom
Website: https://EliElrom.com
License: MIT License
Component: src/component/TemplateName/TemplateName.tsx
*/
import React from 'react';
import './TemplateName.scss';
import { RouteComponentProps } from 'react-router-dom'
export default class TemplateName extends React.PureComponent<ITemplateNameProps, ITemplateNameState> {
  constructor(props: ITemplateNameProps) {
    super(props);
    this.state = {
      name: this.props.history.location.pathname.substring(
        1,
        this.props.history.location.pathname.length
      ).replace('/', '')
    }
  }
  // If you need 'shouldComponentUpdate' -> Refactor to React.Component
  // Read more about component lifecycle in the official docs:
  // https://reactjs.org/docs/react-component.html
  /*
  public shouldComponentUpdate(nextProps: IMyPageProps, nextState: IMyPageState) {
    // invoked before rendering when new props or state are being received.
    return true // or prevent rendering: false
  } */
  static getDerivedStateFromProps:
    React.GetDerivedStateFromProps<ITemplateNameProps, ITemplateNameState> = (props:ITemplateNameProps, state: ITemplateNameState) => {
    // invoked right before calling the render method, both on the initial mount and on subsequent updates
    // return an object to update the state, or null to update nothing.
    return null
  }
  public getSnapshotBeforeUpdate(prevProps: ITemplateNameProps, prevState: ITemplateNameState) {
    // invoked right before the most recently rendered output is committed
    // A snapshot value (or null) should be returned.
    return null
  }
  componentDidUpdate(prevProps: ITemplateNameProps, prevState: ITemplateNameState, snapshot: ITemplateNameSnapshot) {
    // invoked immediately after updating occurs. This method is not called for the initial render.
    // will not be invoked if shouldComponentUpdate() returns false.
  }
  render() {
    return (
      <div className="TemplateName">
        {this.state.name} Component
      </div>)
  }
}
interface ITemplateNameProps extends RouteComponentProps<{ name: string }> {
  // TODO
}
interface ITemplateNameState {
  name: string
}
interface ITemplateNameSnapshot {
  // TODO
}
Create an SCSS file template: templates/component/style.scss.
.TemplateName {
  font-family: 'Open Sans', sans-serif;
  font-weight: 700;
}
Create a test file with Enzyme: templates/component/test.tsx.
import React from 'react'
import { shallow } from 'enzyme'
import TemplateName from './TemplateName'
describe('<TemplateName />', () => {
    let component
    beforeEach(() => {
        component = shallow(<TemplateName />)
    });
    test('It should mount', () => {
        expect(component.length).toBe(1)
    })
})
At this point, you should have a template folder with the files shown in Figure 2-9.
../images/503823_1_En_2_Chapter/503823_1_En_2_Fig9_HTML.jpg
Figure 2-9

Template folder structure and files

You can repeat the same steps for components of the type page or anything you like.

Linting: ESLint and Prettier

How neat would it be to have a code review and have someone formatting your code to make sure it’s consistent?

All code in any code base should look like a single person typed it, no matter how many people contributed.

—Rick Waldron, creator of Johnny-Five

Luckily, this can be done.

Lint is a tool for analyzing your code. It is a static code analysis tool created to identify problematic patterns found in code. Prettier is an opinionated code formatter.

Note

Linting is the process of running a program to analyze your code to find potential errors.

Lint tools can analyze your code and warn you of potential errors. For it to work, we need to configure it with specific rules.

It’s not wise to get into a debate about whether there should be two spaces in every newline or a tab, there should be single quotes or double quotes, etc. The idea is to have some sort of a style guide and follow it for consistency. As was nicely said:

Arguments over style are pointless. There should be a style guide, and you should follow it.

—Rebecca Murphey

Airbnb, as part of its style guide, provides an ESLint configuration that anyone can use as their standard.

ESLint is already installed on Create-React-App, but it’s not optimized with a styling guide and for TypeScript.

To set up your project with ESLint and Prettier for TypeScript using Airbnb’s styling guide (which is considered the standard), use the following:
$ yarn add -D --save-exact eslint-config-airbnb eslint-config-airbnb-TypeScript eslint-config-prettier eslint-config-react-app eslint-import-resolver-TypeScript eslint-loader eslint-plugin-flowtype eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react eslint-plugin-react-hooks babel-eslint eslint-plugin-jest @TypeScript-eslint/parser @TypeScript-eslint/eslint-plugin$ yarn add -D --save-exact prettier prettier-eslint prettier-eslint-cli eslint-plugin-prettier

Read my article (https://medium.com/react-courses/react-create-react-app-v3-4-1-a55f3e7a8d6d) for more information.

Follow the instructions at shorturl.at/otuU8 to update the following files or just copy them from the CRA MHL template project.

There are three files that we will configure.
  • .eslintrc: ESLint run commands configuration file.

  • .eslintignore: ESLint ignore files

  • .prettierrc: Prettier run commands configuration file

Lastly, we can update the package.json file’s run scripts so that we can run Lint and format utilities and even run the app build (the production build we will cover later in this book) with just one command.
"scripts": {
    ..
    ..
    ..
    "lint": "eslint --ext .js,.jsx,.ts,.tsx src --color",
    "format": "prettier --write 'src/**/*.{ts,tsx,scss,css,json}'",
    "isready": "npm run format && npm run lint && npm run build"
}
We are ready to let Lint do its job and change our code (see Figure 2-10).
$ yarn run lint
../images/503823_1_En_2_Chapter/503823_1_En_2_Fig10_HTML.jpg
Figure 2-10

Output after running Lint

To run the formatter to clean our code, we can use Yarn as well.
$ yarn run format
Now confirm we can still compile by checking port 3000 or running yarn start if you stopped the process (see Figure 2-11).
$ yarn start
../images/503823_1_En_2_Chapter/503823_1_En_2_Fig11_HTML.jpg
Figure 2-11

Compiling our code after formatting and linting it

Other Useful Libraries

We will install a couple of useful libraries that will come in handy later in the development exercises in this book.

Classnames
Classnames (https://github.com/JedWatson/classnames) is a simple JavaScript utility for conditionally joining classNames together.
$ yarn add -D classnames @types/classnames
Here is an example of its usage:
import classNames from 'classnames'
const footerClasses = classNames('foo', 'bar') // => 'foo bar'
Prop-types
Prop-types is a great little utility (https://github.com/facebook/prop-types) for runtime type checking for React props and similar objects. We are setting our starter project with TypeScript, so we really don’t need this utility, because we will pass TypeScript objects and get type checking. However, just because we are using TS doesn’t mean we are never going to need JS. There are cases such as importing a component from a different project that we may need this little utility.
$ yarn add -D prop-types
You can download the code from here:
https://github.com/Apress/react-and-libraries/tree/master/01/starter-project
Here is an example of its usage:
import PropTypes from "prop-types";
whiteFont: PropTypes.bool
To have Yarn use package.json and download all the dependencies, run the following:
$ yarn start

Additional Useful Utilities

Here are some additional useful utilities:
  • Lodash (https://github.com/lodash/lodash): This makes JS easier by taking the hassle out of working with arrays, numbers, objects, strings, etc.

  • Moment (https://github.com/moment/moment): For working with dates, this is a must-have.

  • Serve (https://github.com/vercel/serve): Install this with $ yarn add serve. It adds a local server. CRA scripts include a run script to publish your app. It will generate a folder called build. We want to be able to test our build code before going to production. You’ll learn more about production build in later chapters.

  • Precache React-snap to working offline: This is an optimizing library that we will use to configure our app to work offline. See Chapter 11.

  • react-helmet change header metadata: This updates a header of each page for SEO; you’ll learn more in Chapter 11.

  • Analyzer Bundle: You can install the source-map-explorer and cra-bundle-analyzer tools to look inside our JS bundle chunks (more in Chapter 11).

Summary

In this chapter, we learned about the Create-React-App project and set up our starter project and development environment with essential libraries we will be learning about through this book. We installed the CRA MHL template project that already includes everything we need, as well as learned about vanilla CRA and the TypeScript template.

We also learned about libraries such as NPM, Yarn, Webpack, NPM scripts, TypeScript, Sass/SCSS, Redux Toolkit, Material-UI, Styled Components, Router, Jest and Enzyme, Generate templates, and ESLint and Prettier as well as other useful libraries.

In the next chapter, we will be building React custom components and subcomponents.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.223.172.252